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)?
1 Answer
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")));
}
});
6 Comments
TheLeonKing
Thank you very much! What if I wanted to do this for the Name, which is a string?
Louis Wasserman
Then just write
Comparator.comparing(map -> map.get("Name")).TheLeonKing
I'm sorry, I'm using Android Studio, which doesn't have Java 8. What would be the non-Java 8 version?
Louis Wasserman
Them the body of your
compare method is just return a.get("Name").compareTo(b.get("Name")).Andreas
@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. |
[{Name=Pete, Score=1}, {Name=Joe, Score=5}, {Name=Henry, Score=4}]and I want to sort by score.nameandscorerather than aMap<String, String>.