I have created a map called result.
In the sortByKeys method as my keys are String with Numeric values, I have converted them to Integer key type Map then sorted them.
Map<String, String> unsortMap = new TreeMap<String, String>();
unsortMap.put("room~1", "e");
unsortMap.put("room~2", "y");
unsortMap.put("room~10", "n");
unsortMap.put("room~4", "j");
unsortMap.put("room~5", "m");
unsortMap.put("room~3", "f");
Set set2 = unsortMap.entrySet();
Iterator iterator2 = set2.iterator();
while (iterator2.hasNext()) {
/* Iterate */
Map.Entry me2 = (Map.Entry) iterator2.next();
String key = (String) me2.getKey();
Object value = (Object) me2.getValue();
System.out.println("Key ==>" + key + " Value ==>" + value);
}
# Current Output:#
/* current result */
Key ==>room~1 Value ==>e
Key ==>room~10 Value ==>n
Key ==>room~2 Value ==>y
Key ==>room~3 Value ==>f
Key ==>room~4 Value ==>j
Key ==>room~5 Value ==>m
#Expected O/p:#
/* required result */
Key ==>room~1 Value ==>e
Key ==>room~2 Value ==>y
Key ==>room~3 Value ==>f
Key ==>room~4 Value ==>j
Key ==>room~5 Value ==>m
Key ==>room~10 Value ==>n