Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeMap how does it sort

How does the TreeMap sort? say for example you have the following map:

TreeMap<String, Integer> treemap = new TreeMap<>();
treemap.put("lol", 1);
treemap.put("Marc", 2);
treemap.put("Jesper", 3);

Iterator ittwo = treemap.entrySet().iterator();
    while (ittwo.hasNext()) {
    Map.Entry pairs = (Map.Entry)ittwo.next();
    System.out.println(pairs.getKey() + " = " + pairs.getValue());
    ittwo.remove();
}

The output of this is:

Jesper = 3
Marc = 2
lol = 1

So if its not alphabetically what is it then?

like image 901
Marc Rasmussen Avatar asked Nov 30 '12 09:11

Marc Rasmussen


People also ask

How does sorting happen in 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.

Is TreeMap sorted in ascending order?

By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections.

Does TreeMap maintains ascending order?

A TreeMap is a Map that maintains its entries in ascending order, sorted according to the keys' natural ordering, or according to a Comparator provided at the time of the TreeMap constructor argument. The TreeMap class is efficient for traversing the keys in a sorted order.


2 Answers

It is not only alphabetical, but it is also upper/down case sensitive.

TreeMap<String, Integer> treemap = new TreeMap<String, Integer>();
treemap.put("Lol", 1);
treemap.put("Marc", 2);
treemap.put("Jesper", 3);
treemap.put("lol1", 1);
treemap.put("marc1", 2);
treemap.put("jesper1", 3);

Output:

Jesper = 3
Lol = 1
Marc = 2
jesper1 = 3
lol1 = 1
marc1 = 2

So, if you don't need it, you can use your custom comparator, and compare string in lower case:

TreeMap<String, Integer> treemap = new TreeMap<String, Integer>(new Comparator<String>() {
    public int compare(String o1, String o2) {
        return o1.toLowerCase().compareTo(o2.toLowerCase());
    }
});
treemap.put("Lol", 1);
treemap.put("Marc", 2);
treemap.put("Jesper", 3);
treemap.put("lol1", 1);
treemap.put("marc1", 2);
treemap.put("jesper1", 3);

Output:

Jesper = 3
jesper1 = 3
Lol = 1
lol1 = 1
Marc = 2
marc1 = 2
like image 87
kornero Avatar answered Oct 08 '22 23:10

kornero


As stated in the JavaDoc a TreeMap "...is sorted according to the natural ordering of its keys..." (emphasis is mine).

Thus your result is correct, in the light that lower case l is after uppercase M in the UTF "alphabet".

Should you wish to override the default behavior, you can supply a Comparator to the TreeMap constructor.

like image 23
Anders R. Bystrup Avatar answered Oct 09 '22 00:10

Anders R. Bystrup