简体   繁体   中英

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}

The natural ordering of String s 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.

Javadoc says :

The map is sorted according to the natural ordering of its keys , or by a Comparator provided at map creation time, depending on which constructor is used.

EDIT : Eran's answer is right, String ordering is case sensitive by default.

As answered before string natural order is case sensitive. But, if you want insentive ordering, you can provide comparator as TreeMap constructor parameter:

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

ps Notice, when using case insentive order keys will compare insentive too:

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

Result is 6 and key is Hello

Maybe this information will be helpful.

In the class TreeMap contains constructors:

  1. TreeMap ()

  2. TreeMap (Comparator comp)

  3. TreeMap (Map m)

  4. TreeMap (SortedMap sm)

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

The second constructor creates an empty collection, the elements of which will be sorted according to the law, which is defined in the transmission comparator.

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

The fourth constructor creates a TreeMap based on existing SortedMap, elements of which will be sorted according to the law transmitted SortedMap.

Note that keys used for the sorting, rather than the value.

树形图中的排序基于键的自然顺序而不是值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM