Reverse sort a map by its values

In modern world there are many better ways of reversing a HashMap on the basis of the values. This code belongs to old league but you might find it useful

 public static Map reverseSortByValue(Map map, int v)
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
            public int compare(java.util.Map.Entry o1, java.util.Map.Entry o2)
                return ((Comparable)o2.getValue()).compareTo(o1.getValue());
            public volatile int compare(Object obj, Object obj1)
                return compare((java.util.Map.Entry)obj, (java.util.Map.Entry)obj1);
        Map result = new LinkedHashMap();
        int i = 0;
        java.util.Map.Entry entry;
        for(Iterator iterator = list.iterator(); iterator.hasNext(); result.put(entry.getKey(), (Comparable)entry.getValue()))
            entry = (java.util.Map.Entry);
            if(++i > v)
        return result;

Uday Ogra

Connect with me at and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *