Why is my TreeMap not sorting?

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

Here is 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 as follows:

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

But instead, I get the following:

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

+8
java treemap
source share
5 answers

The natural ordering of String case sensitive, so Z precedes w (all uppercase letters apply to all lowercase letters).

Using

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

for case insensitive order.

+16
source share

Javadoc says:

The map is sorted according to the natural order of its keys or the comparator provided when creating the map, depending on which constructor is used.

EDIT: Eran's answer is correct, string ordering is case sensitive by default.

+2
source share

As said before the line, the natural order is case sensitive. But, if you want unobtrusive ordering, you can provide a comparator as a parameter to the TreeMap constructor:

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

ps Please note that when using random letter orders, keys will also compare immodest:

 m.put("Hello", 1); m.put("helLo", 6); 

The result is 6, and the Hello key

+1
source share

Perhaps this information will be helpful.

The TreeMap class contains constructors:

  • TreeMap ()

  • TreeMap (Compator comp)

  • TreeMap (Map m)

  • TreeMap (SortedMap sm)

The first constructor creates a collection in which all elements are sorted in the natural order of their keys.

The second constructor creates an empty collection, elements that will be sorted in accordance with the law, which is defined in the transfer comparator.

The third constructor creates a TreeMap based on the existing Map.

The fourth constructor creates a TreeMap based on the existing SortedMap, the elements of which will be sorted in accordance with the law passed to SortedMap.

Note that the keys used to sort are not the value.

+1
source share

Sorting in treemap is based on the natural order of keys, not values.

0
source share

All Articles