Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my TreeMap not sorting?

Tags:

java

treemap

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}

like image 587
user3248186 Avatar asked Dec 22 '15 07:12

user3248186


People also ask

How do I sort a TreeMap?

A TreeMap is always sorted based on keys. The sorting order follows the natural ordering of keys. You may also provide a custom Comparator to the TreeMap at the time of creation to let it sort the keys using the supplied Comparator. A TreeMap cannot contain duplicate keys.

Does a TreeMap automatically sort?

Default Sorting in TreeMapBy default, TreeMap sorts all its entries according to their natural ordering. For an integer, this would mean ascending order and for strings, alphabetical order.

Are TreeMap values sorted?

In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys. The elements in TreeMap are sorted on the basis of keys.

Does TreeMap sort ascending or descending?

By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections. reverseOrder() method in Java and display the elements in descending order of keys.


2 Answers

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.

like image 189
Eran Avatar answered Sep 18 '22 08:09

Eran


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.

like image 33
Gaël J Avatar answered Sep 19 '22 08:09

Gaël J