I am trying to sorting HashMap data in acending order by using below code :
public static void main(String[] args) {
Map<String, String> unsortMap = new HashMap<String, String>();
unsortMap.put("10", "z");
unsortMap.put("5", "b");
unsortMap.put("6", "a");
unsortMap.put("20", "c");
unsortMap.put("1", "d");
unsortMap.put("7", "e");
unsortMap.put("8", "y");
unsortMap.put("99", "n");
unsortMap.put("50", "j");
unsortMap.put("2", "m");
unsortMap.put("9", "f");
System.out.println("Unsort Map......");
printMap(unsortMap);
System.out.println("\nSorted Map......");
Map<String, String> treeMap = new TreeMap<String, String>(unsortMap);
printMap(treeMap);
}
public static void printMap(Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
}
Output of this program :
Sorted Map......
Key : 1 Value : d
Key : 10 Value : z
Key : 2 Value : m
Key : 20 Value : c
Key : 5 Value : b
Key : 50 Value : j
Key : 6 Value : a
Key : 7 Value : e
Key : 8 Value : y
Key : 9 Value : f
Key : 99 Value : n
Expected Output :
Sorted Map......
Key : 1 Value : d
Key : 2 Value : m
Key : 5 Value : b
Key : 6 Value : a
Key : 7 Value : e
Key : 8 Value : y
Key : 9 Value : f
Key : 10 Value : z
Key : 20 Value : c
Key : 50 Value : j
Key : 99 Value : n
I know If I used character instead on number (for example 1 as 'A', 2 as 'C', .. 99 as 'E') then above code print the correct result. But why its not working when I used integer as string type in key?