Categories: Snippets

Sorting HashMap by values in ascending and descending order

The below example shows Java program to sort a Map by values in ascending and descending order, you can see that it’s so easy to sort the Map.

public static void main(String args[]) {

 Map < String, Integer > map = new HashMap < String, Integer > ();
 map.put("A", 34);
 map.put("B", 25);
 map.put("C", 50);
 map.put("D", 50); // "duplicate" value

 System.out.println(entriesSortedByValues(map));
}

static < K, V extends Comparable < ? super V >> List < Entry < K, V >> entriesSortedByValues(Map < K, V > map) {

 List < Entry < K, V >> sortedEntries = new ArrayList < Entry < K, V >> (map.entrySet());

 Collections.sort(sortedEntries, new Comparator < Entry < K, V >> () {
  @Override
  public int compare(Entry < K, V > e1, Entry < K, V > e2) {
   //return e1.getValue().compareTo(e2.getValue()); // if ascending order
   return e2.getValue().compareTo(e1.getValue()); // if descending order
  }
 });

 return sortedEntries;
}

 

Recent Posts

Read Input from User

In Java, there are three different ways for reading input from the user in the…

6 years ago

Get jsp response as a string inside servlet

To get jsp response as a string inside servlet is possible by wrapping the HttpServletResponse…

6 years ago

Find Upper Case & Lower Case

Given a string, bellow it shows the boolean condition to find Lowercase characters, Uppercase characters.…

6 years ago