0

I have a ArrayList<HashMap<String, String>>, which I want to sort by the value of the HashMap. What would be the quickest way to do this in Java (with the least amount of code)?

4
  • 3
    Which value of the HashMap? It may have many values, in an undefined iteration order. Commented Nov 26, 2015 at 19:25
  • @LouisWasserman Thanks for your quick response. My ArrayList looks like this: [{Name=Pete, Score=1}, {Name=Joe, Score=5}, {Name=Henry, Score=4}] and I want to sort by score. Commented Nov 26, 2015 at 19:29
  • 3
    It looks like you want a custom object with two fields name and score rather than a Map<String, String>. Commented Nov 26, 2015 at 19:35
  • what are your ideas so far? for example you could look at Collections.sort() or at a Comparator-based approach; you could then measure runtime performance for inputs of different sizes Commented Nov 26, 2015 at 21:22

1 Answer 1

3

If you are using Java 8, you'd probably be best off writing

list.sort(Comparator.comparingInt(map -> Integer.parseInt(map.get("Score"))));

If not, you're probably best off writing

Collections.sort(list, new Comparator<Map<String, String>>() {
   @Override public int compare(Map<String, String> a, Map<String, String> b) {
      return Integer.compare(
         Integer.parseInt(a.get("Score")),
         Integer.parseInt(b.get("Score")));
   }
});
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you very much! What if I wanted to do this for the Name, which is a string?
Then just write Comparator.comparing(map -> map.get("Name")).
I'm sorry, I'm using Android Studio, which doesn't have Java 8. What would be the non-Java 8 version?
Them the body of your compare method is just return a.get("Name").compareTo(b.get("Name")).
@Algorithm_NL This answer is great for your stated question, but you'd be better off following Paul Boddington's comment and replace the HashMap with a custom object with two fields name and score. You can then make the object implement Comparable and you won't need an anonymous Comparator.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.