Saturday, November 15, 2014

Sort a Map by value in Java

In Java, you simply use a TreeMap to have a map sorted by key.

But quite often, we need to sort a map by its value.

The method below will help you sort a map by its value. Simply use it in your code.

private static Map<String, String> sortMapByValue(Map<String, String> unsortMap) {
 // Convert Map to List
 List<Map.Entry<String, String>> list = 
  new LinkedList<Map.Entry<String, String>>(unsortMap.entrySet());

 // Sort list with comparator, to compare the Map values
 Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
  public int compare(Map.Entry<String, String> o1,
          Map.Entry<String, String> o2) {
   return (o1.getValue()).compareTo(o2.getValue());
  }
 });

 // Convert sorted map back to a Map
 Map<String, String> sortedMap = new LinkedHashMap<String, String>();
 for (Iterator<Map.Entry<String, String>> it = list.iterator(); it.hasNext();) {
  Map.Entry<String, String> entry = it.next();
  sortedMap.put(entry.getKey(), entry.getValue());
 }
 return sortedMap;
}


Cheers!

No comments:

Post a Comment