java.util.TreeSet Class

The other concrete Set implementation is the TreeSet. The TreeSet class works exactly the same as the HashSet class with one notable exception: instead of keeping its elements unordered, a TreeSet keeps its elements ordered internally. Not only are the elements ordered, but the tree is balanced. More specifically, it's a red−black tree. Having a balanced tree guarantees a quick o(log n) search time at the cost of a more time−intensive insertion (and deletion). Of course, elements added to the tree must be orderable.

Red−black tree rules:
  1. Every node in the tree is either black or red.
  2. The root is always black.
  3. If a node is red, its children must be black.
  4. Every path from the root to a leaf (or null child) must contain the same number of black nodes.

Because TreeSet implements the SortedSet interface as well as the Set interface, understanding TreeSet is a little more involved than HashSet. HashSet class has following constructors.

In order to maintain an ordering, elements added to a tree set must provide some way for the tree to order them. If the elements implement the Comparable interface, the first constructor is sufficient. If, however, the objects aren't comparable or you don't like the default ordering provided, you can pass along a custom Comparator to the constructor that will be used to keep elements ordered. Once the TreeSet is created, you cannot change the comparator.

This java TreeSet tutorial also helpful for the following questions:
  1. How TreeSet works internally in java ?
  2. TreeSet internal implementation in java ?
  3. How TreeSet works in java ?
  4. Internal implementation of TreeSet in java ?
  5. Internal working of TreeSet in java ?

TreeSet()

Constructs a new, empty tree set, sorted according to the natural ordering of its elements.

TreeSet(Collection<? extends E> c)

Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.

TreeSet(Comparator<? super E> comparator)

Constructs a new, empty tree set, sorted according to the specified comparator.

TreeSet(SortedSet < E > s)

Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.

In this tutorial you can learn about java.util.TreeSet class and its examples. And also learn how to use java.util.TreeSet class.

java.util.TreeSet class Example
/* Save with file name TreeSetExample.java */

import java.util.TreeSet;

public class TreeSetExample
{
	public static void main(String args[])
	{
		//java.util.TreeSet DECLARATION
		TreeSet ts;

		//java.util.TreeSet OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		ts = new TreeSet();

		//ADD AN ELEMENT
		ts.add("Huda Tutorials");
		ts.add("Java Tutorials");

		//DUPLICATES NOT ALLOWED
		ts.add("Huda Tutorials");
		ts.add("C Tutorials");
		ts.add("CPP Tutorials");

		//RETURNS COUNT OF ELEMENTS TreeSet CONTAINS
		System.out.println("Elements Count : " + ts.size());

		//java.util.TreeSet OUTPUT
		System.out.println(ts);
	}
}
                        

The following example shows how to use TreeSet with Iterator.

java.util.TreeSet class Example 2
/* Save with file name TreeSetExample2.java */

import java.util.TreeSet;
import java.util.Iterator;

public class TreeSetExample2
{
	public static void main(String args[])
	{
		//java.util.TreeSet DECLARATION
		TreeSet ts;

		//java.util.TreeSet OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		ts = new TreeSet();

		//ADD AN ELEMENT
		ts.add("Huda Tutorials");
		ts.add("Java Tutorials");

		//DUPLICATES NOT ALLOWED
		ts.add("Huda Tutorials");
		ts.add("C Tutorials");
		ts.add("CPP Tutorials");

		//RETURNS COUNT OF ELEMENTS TreeSet CONTAINS
		System.out.println("Elements Count : " + ts.size());

		//java.util.TreeSet OUTPUT
		Iterator itr = ts.iterator();
		while(itr.hasNext())
		{
			System.out.println(itr.next());
		}
	}
}
                        

The following example shows how to use TreeSet with Arrays, Set and Iterator in descending order.

java.util.TreeSet class Example 3
/* Save with file name TreeSetExample3.java */

import java.util.TreeSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Iterator;

public class TreeSetExample3
{
	public static void main(String args[])
	{
		String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
		TreeSet ts; //java.util.TreeSet DECLARATION

		//java.util.Set OBJECT CREATION USING ARRAY AS LIST
		//USING DEFAULT CONSTRUCTOR
		ts = new TreeSet(Arrays.asList(elements));

		//java.util.TreeSet OUTPUT
		Iterator itr = ts.descendingIterator();
		while(itr.hasNext())
		{
			System.out.println(itr.next());
		}
	}
}
                        
java.util.TreeSet class Example 4
/* Save with file name TreeSetExample4.java */

import java.util.TreeSet;
import java.util.Arrays;
import java.util.Iterator;

public class TreeSetExample4
{
	public static void main(String args[])
	{
		String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
		TreeSet s; //java.util.TreeSet DECLARATION

		//java.util.TreeSet OBJECT CREATION USING ARRAY AS LIST
		s = new TreeSet(Arrays.asList(elements));

		//ADD ELEMENT TO Set COLLECTION
		s.add("NetBeans Tutorials");

		//DISPLAY SIZE OF THE Set COLLECTION
		System.out.println("TreeSet Collection Size : "+s.size());

		//CHECK THE Set COLLECTION IS EMPTY
		System.out.println("TreeSet Collection is Empty : "+s.isEmpty());

		//CHECK THE GIVEN ELEMENT IN Set COLLECTION
		System.out.println("\"Huda Tutorials\" Contains :"+s.contains("Huda Tutorials"));

		//RETURNS FIRST LOWEST ELEMENT
		System.out.println("First :"+s.first());

		//RETURNS LAST ELEMENT
		System.out.println("Last :"+s.last());

		//java.util.Set OUTPUT
		System.out.println();
		System.out.println("Elements Before Element Remove");
		System.out.println("------------------------------");
		Iterator itr = s.iterator();
		while(itr.hasNext())
		{
			System.out.println(itr.next());
		}

		s.remove("C Tutorials");

		System.out.println();
		System.out.println("Elements After Element Remove");
		System.out.println("------------------------------");
		itr = s.iterator();
		while(itr.hasNext())
		{
			System.out.println(itr.next());
		}
	}
}
                        

The following example shows how to compare two Set Collections.

java.util.TreeSet class Example 5
/* Save with file name TreeSetExample5.java */

import java.util.TreeSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Iterator;

public class TreeSetExample5
{
	public static void main(String args[])
	{
		String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
		String elements2[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};

		//java.util.TreeSet DECLARATION
		Set s, s2;

		//java.util.Set OBJECT CREATION USING ARRAY AS LIST
		//USING DEFAULT CONSTRUCTOR
		s = new TreeSet(Arrays.asList(elements));
		s2 = new TreeSet(Arrays.asList(elements2));

		//COMPARE TWO COLLECTIONS
		System.out.println("Equals : " + s2.equals(s));

		//CONTAINS COLLECTION IN OTHER COLLECTION
		System.out.println("Contains : " + s2.containsAll(s));
	}
}
                        

The following example shows how to save Set Collection into file.

java.util.TreeSet class Example 6
/* java.util.TreeSet class Example 6 */
/* Save with file name TreeSetExample6.java */

import java.util.TreeSet;
import java.util.Set;
import java.util.Arrays;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class TreeSetExample6
{
	public static void main(String args[])
	{
		try
		{
			String elements[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};

			//java.util.TreeSet DECLARATION
			Set s;

			//java.util.Set OBJECT CREATION USING ARRAY AS LIST
			//USING DEFAULT CONSTRUCTOR
			s = new TreeSet(Arrays.asList(elements));

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

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

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

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

The following example shows how to retrieve Set Collection from file.

java.util.TreeSet class Example 7
/* Save with file name TreeSetExample7.java */

import java.util.TreeSet;
import java.util.Set;
import java.util.Arrays;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class TreeSetExample7
{
	public static void main(String args[])
	{
		try
		{
			//java.util.TreeSet DECLARATION
			Set s;

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

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

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

The following example shows how to create a tree with a Comparator, filling the tree, and getting that comparator.

java.util.TreeSet class Example 8
/* Save with file name TreeSetExample8.java */

import java.util.TreeSet;
import java.util.Collections;

public class TreeSetExample8
{
	public static void main(String args[])
	{
		//java.util.TreeSet DECLARATION
		TreeSet ts;

		//java.util.TreeSet OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		ts = new TreeSet(Collections.reverseOrder());

		//ADD AN ELEMENT
		ts.add("Huda Tutorials");
		ts.add("Java Tutorials");
		ts.add("C Tutorials");
		ts.add("CPP Tutorials");

		//java.util.TreeSet OUTPUT
		System.out.println(ts);

		//java.util.TreeSet Comparator
		System.out.println(ts.comparator());
	}
}