Tuesday, January 25, 2011

Sorting a hashmap by values?

Hash map is a really useful data structure when it comes to coding. In some instances you may need to sort the keys of the hash map according to the values.

Here's a way (there may be many other ways), how you can retrieve the  list of keys after sorting the hash map according to values.

public ArrayList<String> sortHashMapByValues(HashMap<String, Integer> passedMap) {

        ArrayList<String> sortedRels = new ArrayList<String>();
        ArrayList<Integer> mapValues = new ArrayList<Integer>(passedMap.values());
        Collections.sort(mapValues);

        for(int i : mapValues){
            for ( Iterator it = passedMap.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry e = (Map.Entry) it.next();
                if(((Integer)e.getValue()) == i){
                    sortedRels.add((String)e.getKey());
                    passedMap.remove(e.getKey());
                    break;
                }
            }
        }
        return sortedRels;
    }


Hope this is help someone!

1 comment:

tommy chheng said...

Here's another way using a comparator
http://tommy.chheng.com/2009/12/12/sorting-a-hashmap-by-value-in-java-ruby/