i want to sort map according to its key value plz see code below
public static void main(String[] args) {
SortedMap map = new TreeMap();
// Add some elements:
map.put("2", "Two");
map.put("1", "One");
map.put("5", "Five");
map.put("4", "Four");
map.put("3", "Three");
map.put("10", "Ten");
map.put("12", "Twelve");
map.put("7", "Seven");
map.put("9", "Nine");
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
System.out.println("key : " + key + " value :" + map.get(key));
}
}
Result Should come below
key : 1 value :One
key : 2 value :Two
key : 3 value :Three
key : 4 value :Four
key : 5 value :Five
key : 7 value :Seven
key : 9 value :Nine
key : 10 value :Ten
key : 12 value :Twelve
I guess your problem is that keys "10" and "12" come before "2" (btw you should be more specific about your problem next time). This is simply due to the way strings are sorted.
If you want the keys to be sorted according to their integer values, you have the following options:
Integer keys instead of Strings"01" instead of "1" etc.Comparator which sorts according to your wish.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With