Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Map in Java

Tags:

java

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
like image 640
kalpesh Avatar asked Jun 23 '26 10:06

kalpesh


1 Answers

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:

  • use Integer keys instead of Strings
  • insert leading zeroes into the string keys to make them equally long, i.e. "01" instead of "1" etc.
  • use a special Comparator which sorts according to your wish.
like image 69
Péter Török Avatar answered Jun 26 '26 00:06

Péter Török



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!