Search code examples
javacollectionstreemap

TreeMap iteration does not give me sorted keys


I have the below Java code excert. I am expecting to see the keys printed in a sorted manner (since I am using a TreeMap), but it is not sorting the keys. What I am missing?

CODE:

public class TreeMapTest {
    static TreeMap<String,String> li=new TreeMap<String,String>();

    static void readAndPrint(){
        for (Map.Entry<String, String> entry:li.entrySet() ){
            System.out.println(entry);
        }

    }
    public static void main(String[] args) {
        for (int i=0;i<10;i++){
            String key = String.valueOf(new Random().nextInt(100));
            String item = UUID.randomUUID().toString().substring(30);
            li.put(key,item);
            System.out.println(MessageFormat.format("inserting ({0},{1})",key,item));
        }

        readAndPrint();
    }
} 

Sample output:

inserting (7,f4b66a)
inserting (2,5f417d)
inserting (51,90bb9f)
inserting (99,4bfb73)
inserting (41,a4e9d5)
inserting (14,9286d6)
inserting (44,ec4fbd)
inserting (58,e7dd3a)
inserting (69,c54e66)
inserting (0,d1fbfe)
0=d1fbfe
14=9286d6
2=5f417d
41=a4e9d5
44=ec4fbd
51=90bb9f
58=e7dd3a
69=c54e66
7=f4b66a
99=4bfb73

As you see I am not getting the elements sorted ( I sometimes have the output sorted and sometime have it not sorted as above!). What I am missing or misunderstanding?


Solution

  • They are sorted, by the default sort order of Strings. Strings are ordered lexicographically, so "14" is considered less than "2".

    If you want numerical sort order, you should have made the keys Integers instead of Strings.