Constructors and methods of TreeMap in Java

There are four constructors defined for Hashtable.

  • TreeMap()
  • TreeMap(Comparator comparator)
  • TreeMap(Map m)
  • TreeMap(SortedMap m)

TreeMap() – This is default constructor which is used to create new and empty TreeMap, sort the added elements in ascending order on basis of the key. All keys inserted into the map must implement the Comparable interface. Wrapper classes are best keys for TreeMap because all Wrapper classes implement the Comparable interface.

package treemapexample;
import java.util.*;
public class Example1 {
public static void main(String[] args) {
	
	//Creating TreeMap object using default constructor
	Map<Integer, String> treeMapObject = new TreeMap<>();
	treeMapObject.put(2, "ram");
	treeMapObject.put(8, "mohan");
	treeMapObject.put(3, "sohan");
	treeMapObject.put(4, "rahul");
	treeMapObject.put(9, "rohan");
	treeMapObject.put(0, "suresh");
	treeMapObject.put(1, "ganesh");
	Iterator<Map.Entry<Integer, String>> iterator = treeMapObject
			.entrySet().iterator();
 
	while (iterator.hasNext()) {
		Map.Entry<Integer, String> entry = iterator.next();
		System.out.println("Key is = " + entry.getKey() + ", Value is = "
				+ entry.getValue());
	}
}
}

Output –

Key is = 0, Value is = suresh
Key is = 1, Value is = ganesh
Key is = 2, Value is = ram
Key is = 3, Value is = sohan
Key is = 4, Value is = rahul
Key is = 8, Value is = mohan
Key is = 9, Value is = rohan


In the above example we can see it has been sorted on basis of key.

TreeMap(Comparator comparator) – We can pass any class object which implements Comparator interface.


TreeMap(Map m) – We can pass any type of classes which implements Map interface and can convert it into TreeMap. For example, we are going to convert HashMap into TreeMap in below example before that let’s see how this constructor has been defined in TreeMap class.

package treemapconstructor;

import java.text.Collator;
import java.util.*;
 
public class Example2 {
	public static void main(String[] args) {
 
		    //creating HashMap object using, later we will convert into TreeMap
				Map<Integer, String> hashMapObject = new HashMap<>();
				 
				hashMapObject.put(2, "ram");
				hashMapObject.put(8, "mohan");
				hashMapObject.put(4, "Bangalore");
				hashMapObject.put(5, "Rakesh");
				
		 
				// we will convert HashMap into TreeMap using below constructor
				TreeMap<Integer,String> treeMapObj = new TreeMap<>(hashMapObject);
				Iterator<Map.Entry<Integer, String>> iterator = treeMapObj
						.entrySet().iterator();
		 
				while (iterator.hasNext()) {
					Map.Entry<Integer, String> entry = iterator.next();
					System.out.println("Key is = " + entry.getKey() + ", Value is = "
							+ entry.getValue());
				}
	}
}

Output is –

Key is = 2, Value is = ram
Key is = 4, Value is = Bangalore
Key is = 5, Value is = Rakesh
Key is = 8, Value is = mohan