java.util.TreeMap Class

A TreeMap is a map that maintains its keys ordered within a balanced, red−black tree. 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.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. TreeMap is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

TreeMap class has following constructors.

TreeMap()

Constructs a new, empty tree map, using the natural ordering of its keys.

TreeMap(Comparator < ? super K > comparator)

Constructs a new, empty tree map, ordered according to the given comparator.

TreeMap(Map < ? extends K,? extends V > m)

Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.

TreeMap(SortedMap < K,? extends V > m)

Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map.

java.util.TreeMap class Example
/* Save with file name TreeMapExample.java */

import java.util.TreeMap;
import java.util.Enumeration;

public class TreeMapExample
{
	public static void main(String args[])
	{
		//java.util.TreeMap DECLARATION
		TreeMap <String,Integer> h;

		//java.util.TreeMap OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		h = new TreeMap <String,Integer>();

		//ADD KEY AND VALUE
		h.put("ONE", new Integer(1));
		h.put("TWO", new Integer(2));
		h.put("THREE", new Integer(3));

		//ALLOW null VALUE ONLY
		h.put("FOUR",null);

		//TreeMap OUTPUT
		System.out.println(h);
	}
}
                        
java.util.TreeMap class Example 2
/* Save with file name TreeMapExample2.java */

import java.util.TreeMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Collection;
import java.util.Iterator;

public class TreeMapExample2
{
	public static void main(String args[])
	{
		//java.util.TreeMap DECLARATION
		TreeMap <String,Integer> h;

		//java.util.TreeMap OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		h = new TreeMap <String,Integer>();

		//ADD KEY AND VALUE
		h.put("ONE", new Integer(1));
		h.put("TWO", new Integer(2));
		h.put("THREE", new Integer(3));

		//ALLOW null VALUE ONLY
		h.put("FOUR",null);

		//TreeMap KEYS OUTPUT
		Set s = h.keySet();
		Iterator itr = s.iterator();
		int i=1;
		while(itr.hasNext())
		{
			System.out.println("Key " + i++ + " : " + itr.next());
		}

		//TreeMap VALUES OUTPUT
		Collection c = h.values();
		Iterator values = c.iterator();
		int j=1;
		while(values.hasNext())
		{
			System.out.println("Value " + j++ + " : " + values.next());
		}
	}
}
                        
java.util.TreeMap class Example 3
/* Save with file name TreeMapExample3.java */

import java.util.TreeMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
import java.util.Collection;
import java.util.Iterator;

public class TreeMapExample3
{
	public static void main(String args[])
	{
		//java.util.TreeMap DECLARATION
		TreeMap <String,Integer> h;

		//java.util.TreeMap OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		h = new TreeMap <String,Integer>();

		//ADD KEY AND VALUE
		h.put("ONE", new Integer(1));
		h.put("TWO", new Integer(2));
		h.put("THREE", new Integer(3));

		//ALLOW null VALUE ONLY
		h.put("FOUR",null);

		//TreeMap KEYS OUTPUT
		Set s = h.entrySet();
		Iterator itr = s.iterator();
		int i=1;
		while(itr.hasNext())
		{
			//Map.Entry IS INNER INTERFACE OF Map INTERFACE
			Map.Entry entry = (Map.Entry) itr.next();
			System.out.println(entry.getKey()+" "+entry.getValue());
		}
	}
}
                        
java.util.TreeMap class Example 4
/* Save with file name TreeMapExample4.java */

import java.util.TreeMap;
import java.util.Enumeration;

public class TreeMapExample4
{
	public static void main(String args[])
	{
		//java.util.TreeMap DECLARATION
		TreeMap <String,Integer> h;

		//java.util.TreeMap OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		h = new TreeMap <String,Integer>();

		//ADD AN ELEMENTS
		h.put("ONE", new Integer(1));
		h.put("TWO", new Integer(2));
		h.put("THREE", new Integer(3));

		System.out.println("isEmpty : " + h.isEmpty());

		//RETURNS THE NUMBER OF KEYS IN THIS TreeMap
		System.out.println("noof Keys : " + h.size());

		System.out.println("Key ONE value : " + h.get("ONE"));

		System.out.println("Contains key THREE : " + h.containsKey("THREE"));

		System.out.println("Contains value 2 : " + h.containsValue(new Integer(2)));
	}
}
                        

The following example shows how to save TreeMap into file.

java.util.TreeMap class Example 5
/* Save with file name TreeMapExample5.java */

import java.util.TreeMap;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class TreeMapExample5
{
	public static void main(String args[])
	{
		try
		{
			//java.util.TreeMap DECLARATION
			TreeMap <String,Integer> h;

			//java.util.TreeMap OBJECT CREATION
			//USING DEFAULT CONSTRUCTOR
			h = new TreeMap <String,Integer>();

			//ADD AN ELEMENTS
			h.put("ONE", new Integer(1));
			h.put("TWO", new Integer(2));
			h.put("THREE", new Integer(3));

			//FileOutputStream CREATION
			FileOutputStream fos = new FileOutputStream("treemap.set");

			//ObjectOutputStream CREATION
			ObjectOutputStream oos = new ObjectOutputStream(fos);

			//WRITE Set OBJECT TO ObjectOutputStream
			oos.writeObject(h);

			//CLOSE THE ObjectOutputStream
			oos.close();
			System.out.println("TreeMap Saved into File Sucessfully");
		}
		catch(Exception e)
		{
			System.out.println("Error Occurred : " + e.getMessage());
		}
	}
}
                        

The following example shows how to retrieve TreeMap from file.

java.util.TreeMap class Example 6
/* Save with file name TreeMapExample6.java */

import java.util.TreeMap;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class TreeMapExample6
{
	public static void main(String args[])
	{
		try
		{
			//java.util.TreeMap DECLARATION
			TreeMap <String,Integer> h;

			//FileInputStream CREATION
			FileInputStream fis = new FileInputStream("treemap.set");

			//ObjectInputStream CREATION
			ObjectInputStream ois = new ObjectInputStream(fis);

			//READ TreeMap OBJECT FROM ObjectInputStream
			h = (TreeMap) ois.readObject();
			ois.close();
			System.out.println(h);
		}
		catch(Exception e)
		{
			System.out.println("Error Occurred : " + e.getMessage());
		}
	}
}