I want to sort map in descending order by value and print only key having highest value Note: print multiple key if both have same value
map.put(5,3);
map.put(4,1);
map.put(2,2);
map.put(10,3);
Set <Map.Entry<Integer,Integer>>set = map.entrySet();
List <Map.Entry<Integer,Integer>> list = new ArrayList<Map.Entry<Integer,Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<Integer,Integer>>(){
public int compare(Map.Entry<Integer,Integer> obj1, Map.Entry<Integer,Integer> obj2){
return (obj2.getValue().compareTo(obj1.getValue()));
}
});
Now i got output 5,10 but i want output as 10,5
-
what do you mean by "sort a map"? Map in general cannot be arbitrary sortedAlex Salauyou– Alex Salauyou2016年03月10日 07:10:23 +00:00Commented Mar 10, 2016 at 7:10
1 Answer 1
If you want a secondary ordering according to keys (i.e. if the values are equal, sort be keys in descending order), add a condition for the case of equal values :
Collections.sort(list, new Comparator<Map.Entry<Integer,Integer>>(){
public int compare(Map.Entry<Integer,Integer> obj1, Map.Entry<Integer,Integer> obj2){
if (!obj2.getValue().equals(obj1.getValue()))
return (obj2.getValue().compareTo(obj1.getValue()));
else
return (obj2.getKey().compareTo(obj1.getKey()));
}
});
answered Mar 10, 2016 at 7:00
Eran
395k57 gold badges726 silver badges793 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-java