Sort a hash map by Integer Value desc

How to sort hashmap by integer value and one of the answers found here

written by Eugene Dorofeev , and his answer was this:

 HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("a", 4); map.put("c", 6); map.put("b", 2); Object[] a = map.entrySet().toArray(); Arrays.sort(a, new Comparator() { public int compare(Object o1, Object o2) { return ((Map.Entry<String, Integer>) o2).getValue().compareTo( ((Map.Entry<String, Integer>) o1).getValue()); } }); for (Object e : a) { System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : " + ((Map.Entry<String, Integer>) e).getValue()); } 

Output

 c : 6 a : 4 b : 2 

My question is: how will sorting become Desc ? and if I want to sort hashmap Asc . How can i do this?

and the last question: how can I get the first item after sorting?

+6
source share
3 answers

For the reverse order switch o2 and o1 . To get the first element, simply access the array with index 0:

 Map<String, Integer> map = new HashMap<>(); map.put("a", 4); map.put("c", 6); map.put("b", 2); Object[] a = map.entrySet().toArray(); Arrays.sort(a, new Comparator() { public int compare(Object o1, Object o2) { return ((Map.Entry<String, Integer>) o1).getValue().compareTo( ((Map.Entry<String, Integer>) o2).getValue()); } }); for (Object e : a) { System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : " + ((Map.Entry<String, Integer>) e).getValue()); } System.out.println("first element is " + ((Map.Entry<String, Integer>) a[0]).getKey() + " : " + ((Map.Entry<String, Integer>) a[0]).getValue()); 

What seal

b: 2
a: 4
c: 6
the first element is b: 2

If you have access to a lambda expression, you can simplify sorting with the following:

 Arrays.sort(a, (o1, o2) -> ((Map.Entry<String, Integer>) o1).getValue().compareTo(((Map.Entry<String, Integer>) o2).getValue())); 
+6
source

In Java 8, you can do something like:

 System.out.println(map.entrySet().stream().sorted((o1, o2) -> { return o2.getValue().compareTo(o1.getValue()); }).findFirst());//would return entry boxed into optional which you can unbox. 
+3
source

First of all, answering your question: just change the result of the compare method to change the ASC to DESC.

 HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("a", 4); map.put("c", 6); map.put("b", 2); Object[] a = map.entrySet().toArray(); Arrays.sort(a, new Comparator() { public int compare(Object o1, Object o2) { // just reverse the result of the comparison return -((Map.Entry<String, Integer>) o2).getValue().compareTo( ((Map.Entry<String, Integer>) o1).getValue()); } }); for (Object e : a) { System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : " + ((Map.Entry<String, Integer>) e).getValue()); } 

But if you need to work with a sorted Map , I suggest you use an instance of TreeMap , which handles the sorting on its own.

+2
source

All Articles