You are on page 1of 5

TreeMap in Java

TreeMap is used to create a map where the keys are


stored in sorted order.
Example-1, Empty TreeMap() constructor
TreeMap studentMap = new
TreeMap<Integer,String>();
treeMap.put(15,"Rohan");
treeMap.put(10,"Gaurav");
treeMap.put(1,"Abhishek");

studentMap ->
{1,"Abhishek",10:"Gaurav",15:"Rohan"}
When used with an empty TreeMap() constructor
the keys are sorted in the natural sorting order,
which is ascending for integer and string keys.

Now, if your keys are not of primitive type then


you need to use another constructor from
TreeMap.
Example-2 TreeMap(Comparator c) -
TreeMap studentMap = new TreeMap<Student,String>
(comparator);
treeMap.put(Student(15),"Dancing");
treeMap.put(Student(1),"Painting");
treeMap.put(Student(10),"Singing");

studentMap ->
{Student(15),"Dancing",Student(10):"Singing",Student(1):
"Painting"}
In Example-2 we passed a comparator (which
sorts in descending order) to the TreeMap
constructor and it sorted the map according to
the Student's roll no in descending order.

TreeMap(map) - In this 3rd constructor we can


pass any map (HashMap, LinkedHashMap etc.)
and it will sort that map too. ding...
Thanks for rea

You might also like