Lets suppose I have the following list of maps
[{id:1,count:2,name:xyz},
{id:2,count:3,name:def},
{id:3,count:2,name:abc},
{id:4,count:5,name:ghj}
]
I first want to sort this map by count and then by name:
Desired Output :
[{id:3,count:2,name:abc},
{id:1,count:2,name:xyz},
{id:2,count:3,name:def},
{id:4,count:5,name:ghj}
]
I tried the following to perform the first sorting,but unable to sort using name after sorting by count
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
With Java 1.8, I would use the new Comparator methods (although the lack of Type inference makes it necessary to declare all types, reducing the lisibility):
With Java 1.7, I would probably use a chainedComparator (see Apache's ComparatorUtils or Guava's Ordering) and a custom MapValueComparator (there are probably one in common libraries, but haven't found it). Then the wanted ordering get quite readable :
And then use it (Java 7 or 8):
Rq: you should, as stated in other answers, check for nulls and absent keys in the MapValueComparator.