08/10/2012

[Java] Sort Map by Keys

If you have a Map (usually a HashMap since a TreeMap is already sorted) and need to sort it by keys, you will find that there's no method you can call directly on it.

What you can do however, is to create a SortedSet (we'll use a TreeSet) of the Map's keys and then use it alongside the Map.

Example:

myMap is a HashMap<K,V>

//Create sorted set from myMap - this already sorts the keys!
SortedSet mySortedMap = new TreeSet(myMap.keySet());
//Loop on it
for(Iterator iter = mySortedMap.iterator(); iter.hasNext();){
     //Obviously, replace K and V with your data types
     K key = (K) iter.next();
     V value = (V) myMap.get(key);
     /* do what you need */
}

If you are luckier than me and use Java 5+ you can type all collections directly in the declaration with the <K,V>syntax and also use the for-each loop to cycle through the sorted set
for(K key : mySortedMap){
     V value = (V) myMap.get(key);
     /* do what you need */ }

No comments:

Post a Comment

With great power comes great responsibility