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}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With