Search code examples
javatreemap

Why is my TreeMap not sorting?


I used a TreeMap where the key is a String and the value is of type Integer. When I output the Map object, it's not printing in sorted order.

Here's the code I used:

TreeMap<String, Integer> m = new TreeMap<String, Integer>();
m.put("Hello", 1);
m.put("world", 2);
m.put("Zertt", 5);
m.put("Hello", 1);
m.put("world", 2);
System.out.println("map : " + m);

I expect the output to be sorted like this :

map : {Hello=1, world=2, Zertt=5}

But instead I get this :

map : {Hello=1, Zertt=5, world=2}


Solution

  • The natural ordering of Strings is case sensitive, so Z comes before w (all upper case letters come before all lower case letters).

    Use

    TreeMap<String, Integer> m = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
    

    for case insensitive order.