user3248186
user3248186

Reputation: 1558

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}

Upvotes: 9

Views: 5979

Answers (5)

Eran
Eran

Reputation: 394156

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.

Upvotes: 21

Javasick
Javasick

Reputation: 3003

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

Upvotes: 1

Sergey Lotvin
Sergey Lotvin

Reputation: 179

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.

Upvotes: 1

Ga&#235;l J
Ga&#235;l J

Reputation: 15305

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.

Upvotes: 2

Avinash Kumar Pandey
Avinash Kumar Pandey

Reputation: 762

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

Upvotes: 0

Related Questions