HOW TO SORT A MAP<KEY, VALUE> ON THE VALUES IN JAVA?

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
 666  View(s)
Ratings:
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?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How to sort a Map<Key, Value> on the values in Java?

    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;
    }  

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!