sorting treemap based on key, where key is variable

sachin picture sachin · Aug 3, 2011 · Viewed 36k times · Source

I want to sort the tree map based on the key where key is a variable,so sorting should be based on variable value, How can we achieve this? I want use in built sort method rathar implementing it through code, any reply with example is of great help.

Answer

pmnt picture pmnt · Aug 3, 2011

TreeMap (which implements SortedMap) stores automatically the keys in the correct order:

Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "one");
map.put(3, "three");
map.put(2, "two"); 
// prints one two three   
for(Integer key : map.keySet()) {
    System.out.println(map.get(key));
}

As Key-Type (in that case Integer) you can use any class which implements Comparable (or you can provide a Comparator when creating the TreeMap)

Edit: Okay, here is a suggestion how to re-map your map.

Map<Integer, String> oldMap; // get oldMap from somewhere
// Prepare remapping
Map<Integer, String> newMap = new TreeMap<Integer, String>();
Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
// Store a new key for each old key
keyMap.put(oldKey, newKey);
// fill the newMap
for(Integer oldKey : keyMap.keySet()) {
    newMap.put(keyMap.get(oldKey), oldMap.get(oldKey));
}
oldMap = newMap; // if needed