How to sort data that’s in a Java HashMap (using a TreeMap)

Here’s a brief example of how to sort data that’s already in a Java HashMap. First, some HashMap data:

import java.util.*;

Map<Integer, Float> playMap = new HashMap<Integer, Float>() {{
    put(10,  1f);
    put(12,  2f);
    put(15,  4f);
    put(18,  6f);
    put(20,  6f);
    put(25,  7f);
    put(30,  6f);
    put(35,  5f);
    put(40,  5f);
}};

A HashMap won’t keep that data in sorted order, so if you want your data sorted, one way to sort it is to add the elements to a Java TreeMap:

TreeMap<Integer, Float> sortedMap = new TreeMap<>();
sortedMap.putAll(playMap);

Now you can verify that the TreeMap data is sorted by printing it:

for (Map.Entry<Integer,Float> entry: sortedMap.entrySet()) {
    System.out.println("Key : " + entry.getKey() + ",  Value : " + entry.getValue());
}

Here’s the output from iterating over those TreeMap keys and values:

Key : 10,  Value : 1.0
Key : 12,  Value : 2.0
Key : 15,  Value : 4.0
Key : 18,  Value : 6.0
Key : 20,  Value : 6.0
Key : 25,  Value : 7.0
Key : 30,  Value : 6.0
Key : 35,  Value : 5.0
Key : 40,  Value : 5.0

As a brief note to self, you can also iterate over the keys and values in a Java Map (HashMap, TreeMap, etc.) using this keySet approach:

for (Object o: sortedMap.keySet()) {
    Integer k = (Integer)o;
    System.out.println("Key : " + k + ",  Value : " + playMap.get(k));
}