Home > DeveloperSection > Forums > How to sort a Map<Key, Value> on the values in Java?
Chintoo Semi

Total Post:135

Points:947
Posted on    May-13-2015 11:47 PM

 Java Java  Collection 
Ratings:


 1 Reply(s)
 407  View(s)
Rate this:
I am relatively new to Java, and often find that I need to sort a Map<Key, Value> on the values. Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key. Is there an easier way?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    May-14-2015 7:36 AM

static Map sortByValue(Map map) {
     List list = new LinkedList(map.entrySet());
     Collections.sort(list, new Comparator() {
          public int compare(Object o1, Object o2) {
               return ((Comparable) ((Map.Entry) (o1)).getValue())
              .compareTo(((Map.Entry) (o2)).getValue());
          }
     });
    Map result = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry)it.next();
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}  

Don't want to miss updates? Please click the below button!

Follow MindStick