HudaTutorials.com

java util TreeMap Class - java.util.TreeMap Class in Java

Last updated on

java.util.TreeMap Class

TreeMap Class in Java

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.

Is TreeMap Thread Safe ?

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.

To prevent accidental unsynchronized access to the map, you should create map with Collections.synchronizedSortedMap method.

What are the Red Black Tree Rules in Java ?

  • Every node in the tree is either black or red.
  • The root is always black.
  • If a node is red, its children must be black.
  • Every path from the root to a leaf (or null child) must contain the same number of black nodes.

java.util.TreeMap class Example

/*	Java 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

/*	Java 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

/*	Java 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

/*	Java 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)));
	}
}

How to save TreeMap into file

The following example shows how to save TreeMap into file.

/*	How to save TreeMap into file Example
	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());
		}
	}
}

How to retrieve TreeMap from file

The following example shows how to retrieve TreeMap from file.

/*	How to retrieve TreeMap from file Example
	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());
		}
	}
}