1

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 
1
  • what do you mean by "sort a map"? Map in general cannot be arbitrary sorted Commented Mar 10, 2016 at 7:10

1 Answer 1

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())); } }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.