Why is my TreeMap not sorting?
Asked Answered
A

5

9

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}

Awn answered 22/12, 2015 at 7:41 Comment(0)
B
21

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.

Bracken answered 22/12, 2015 at 7:42 Comment(0)
S
2

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.

Sasha answered 22/12, 2015 at 7:43 Comment(0)
A
1

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);

p.s. 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

Angeliqueangelis answered 22/12, 2015 at 7:49 Comment(0)
D
1

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.

Deliquescence answered 22/12, 2015 at 7:49 Comment(0)
S
0

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

Slavic answered 22/12, 2015 at 7:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.