Reputation: 1558
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
Reputation: 394156
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.
Upvotes: 21
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
Reputation: 179
Maybe this information will be helpful.
In the class TreeMap contains constructors:
TreeMap ()
TreeMap (Comparator comp)
TreeMap (Map m)
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
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
Reputation: 762
Sorting in treemap is based on the natural order of keys and not values.
Upvotes: 0