19 March, 2013

HashMap sorting

I know this is not related to Liferay... But it can be useful to you guys for java programming...
As we know that hash map doesnt allow duplicate value with the same key name... But if you want to sort the map by values instead of key, below is the code which can be useful...


package com.jignesh.test;
import java.util.*;
import java.util.Map.Entry;

public class Test {

    public static Map<Object, Integer> sortByValue(Map<Object, Integer> map) {
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
           
            @Override
            public int compare(Object o2, Object o1) {
                return ((Comparable) ((Map.Entry) (o2)).getValue())
                        .compareTo(((Map.Entry) (o1)).getValue());
            }
        });

        Map result = new LinkedHashMap();
        HashSet hs = new HashSet();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    public static void main(String[] args) {

        HashMap<Object, Integer> map = new HashMap<Object, Integer>();

        map.put("jignesh1", 1);
        map.put("jignesh2", 2);
        map.put("jignesh3", 1);
        map.put("jignesh4", 7);
        map.put("jignesh5", 3);
        map.put("jignesh6", 4);

        Map<Object, Integer> sortedMap = Test.sortByValue(map);

        for (Entry<Object, Integer> entry : sortedMap.entrySet()) {
            System.out.println("Name is:" + entry.getKey() + " with value:"
                    + entry.getValue());

        }

    }

}

Popular Posts

Featured Post

Liferay 7.3 compatibility matrix

Compatibility Matrix Liferay's general policy is to test Liferay Portal CE against newer major releases of operating systems, open s...