Sunday, August 28, 2016

TreeMap how does it sort??

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.

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

Resource Link:

http://stackoverflow.com/a/13642719/2293534

No comments:

Post a Comment