TreeMap in java with example

Here we will see about TreeMap in java with example.

Basic Points about TreeMap.

  • TreeMap is a class which extends AbstractMap and implements NavigableMap, Cloneable, Serializable.
  • TreeMap also used to store the element in the form of key and value pair.
  • In the TreeMap key must be the same type where value can be the different type.
  • Key cannot be duplicated where value can be duplicated.
  • Treemap store the element in sorted order on the basis of the key.
  • TreeMap uses index representation to store the elements.
  • In TreeMap value can be null but the key cannot be null. If we try to insert null as a key, the code will compile successfully but at runtime, it will throw NullPointerException.
  • In Treemap none of the methods are synchronized so it doesn’t affect the concurrency and cloning.

Example:-

package treemapexample;
import java.util.*;

class TreeMapExp {
	public static void main(String[] arg) {
		Map<Integer, String> treemapObject = new TreeMap<>();
 
		treemapObject.put(4, "ram");
		treemapObject.put(1, "mohan");
		treemapObject.put(3, "Bangalore");
		treemapObject.put(2, "Rakesh");
 
		// we will iterate using Iterator
		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 = 1, Value is = mohan
Key is = 2, Value is = Rakesh
Key is = 3, Value is = Bangalore
Key is = 4, Value is = ram

In above example we can se elements are sorted on the basis of key.

Example: – Inserting null as a key in TreeMap.

package treemapexample;
import java.util.*;

class TreeMapExp {
	
	public static void main(String[] arg) {
		
		Map<Integer, String> treemapObject = new TreeMap<>();
		
	       // passing null as a key in TreeMap
		
		treemapObject.put(null, "ram");
		treemapObject.put(0, "mohan");
		treemapObject.put(3, "Bangalore");
		treemapObject.put(2, "Rakesh");
 
		// we will iterate using Iterator
		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 –

Exception in thread “main” java.lang.NullPointerException
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at treemapexample.TreeMapExp.main(TreeMapExp.java:12)

 

TreeMap Methods.