How to sort the values of a HashMap in Java

Submitted by bill on Thu, 26/06/2008 - 14:16

If you want to sort a HashMap and keep the duplicate entries then see the solution in this article. Otherwise, read this article!

TASK
I want to sort my HashMap entries depending on the value of each one of them. I do not care about duplicate entries - duplicate entries are ignored by using this method. My HashMap is named as unSorted and it has values. In other words, it is defined as:

HashMap<String, Double> unSorted = new HashMap<String, Double>();

Now we put some sample entries in the HashMap, just to have something to order.

unSorted.put("Bristol", 23.45);
unSorted.put("London", 345.122);
unSorted.put("Manchester", 12.3);
unSorted.put("Edinburgh", 11.4); 

Then we write a method that is able to take a HashMap as an input and after doing some crazy staff, it outputs the same HashMap but with its values sorted (ascending).

SOLUTION
This is the source code of the method:

private HashMap<String, Double> sortHashMap(HashMap<String, Double> input){
    Map<String, Double> tempMap = new HashMap<String, Double>();
    for (String wsState : input.keySet()){
        tempMap.put(wsState,input.get(wsState));
    }

    List<String> mapKeys = new ArrayList<String>(tempMap.keySet());
    List<Double> mapValues = new ArrayList<Double>(tempMap.values());
    HashMap<String, Double> sortedMap = new LinkedHashMap<String, Double>();
    TreeSet<Double> sortedSet = new TreeSet<Double>(mapValues);
    Object[] sortedArray = sortedSet.toArray();
    int size = sortedArray.length;
    for (int i=0; i<size; i++){
        sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), 
                      (Double)sortedArray[i]);
    }
    return sortedMap;
}

Now, to retrieve a HashMap with sorted values, you just have to use(!) the method above.

HashMap<String, Double> sorted = new HashMap<String, Double>();
sorted = sortHashMap(unSorted);

If we print the sorted HashMap...

for (String cityName : sorted.keyset()){
    System.out.println(cityName + " " + sorted.get(cityName));
}

we get:

Edinburgh 11.4
Manchester 12.3
Bristol 23.45
London 345.122