Java TreeSet Class | Complete Tutorial | Explained with Coding Examples

Java TreeSet Class | Complete Tutorial | Explained with Coding Examples

The TreeSet class in Java is a member of the Java Collections Framework and is implemented as a red-black tree.

It is a Set data structure that stores unique elements in sorted order. The TreeSet class is part of java.util package and provides a powerful and efficient way to store and retrieve elements in a sorted manner.

One of the main advantages of using TreeSet is that it automatically sorts the elements in the set according to their natural ordering or according to the order specified by a custom comparator. This eliminates the need for manual sorting, making the process much more efficient.

One of the most common use cases for TreeSet is when we need to sort a large number of elements.

For example, if we have a list of names that we need to sort alphabetically, we can simply use the TreeSet to store the names and the elements will be automatically sorted.

Here is an example of how to create and use the TreeSet in java.

Creating TreeSet in Java

To create a TreeSet in java, we can use its constructors. TreeSet class has four constructors such as:

TreeSet()

It is a non-argument constructor and is used to create a new, and empty tree set.

TreeSet​(Collection<? extends E> c)

It creates a new tree set with the specified collection.

TreeSet​(Comparator<? super E> comparator)

This command creates a new tree set and sorts the elements sorted according to the specified comparator.

TreeSet​(SortedSet<E> s)

Creates a new tree set with the specified SortedSet elements.

In the code example below, we created a new tree set with all these constructors to check how it works.

import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Set;
import java.util.SortedSet;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create empty TreeSet
		Set<String> set = new TreeSet<>();
		System.out.println(set);
		
		// Creating TreeSet with existing collection
		Set<String> set2 = new TreeSet<>(Arrays.asList("One","Two","Three","One"));
		System.out.println(set2);
		
		// Creating a sorted set
		SortedSet<Integer> set3 = new TreeSet<>(Arrays.asList(1,3,3,2));
		
		// Creating TreeSet with sorted set
		Set<Integer> set4 = new TreeSet<>(set3);
		System.out.println(set4);
	}	
}

Output:

[]
[One, Three, Two]
[1, 2, 3, 5, 8]

Add Elements to the TreeSet

To add elements into the tree set, we can use its built-in methods such as add(), and addAll(). To understand the working, you can refer to the below code and the code.

package javaexample;

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

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a TreeSet
		Set<String> set = new TreeSet<>();
		System.out.println(set);
		
		// Adding elements
		set.add("One");
		set.add("Two");
		set.add("Three");
		set.add("One");
		
		System.out.println(set);
		
		// Add all from existing collection
		List<String> list = Arrays.asList("Five","Six","Two");
		set.addAll(list);
		System.out.println(set);
	}	
}

Output:

[]
[One, Three, Two]
[Five, One, Six, Three, Two]

Removing elements from the TreeSet

To remove elements of the tree set, we can use remove, and removeAll() methods. The remove method takes a single argument and removes the specified element from the TreeSet. If we want to remove all the elements then use the removeAll() method as done in the below code.

package javaexample;

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

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a tree set
		Set<String> set = new TreeSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// Remove single element
		set.remove("Three");
		System.out.println(set);
		
		// Remove element if string length is more than 5
		set.removeIf(str->(str.length() >= 5));
		System.out.println(set);
		
		// Remove All elements
		set.removeAll(set);
		System.out.println(set);
				
	}	
}

Output:

[One, Seven, Three, Two]
[One, Seven, Two]
[One, Two]
[]

Compare TreeSet

If we have multiple sets and want to check whether they contain similar or distinguished elements. For this purpose, we can use the equals() method that returns a Boolean value either true or false based on equality. You can refer to the below code where we are comparing two TreeSet objects.

package javaexample;

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

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a TreeSet
		Set<String> set = new TreeSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// Create a set
		Set<String> set2 = new TreeSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		if(set.equals(set2)) {
			System.out.println("equal");
		}else {
			System.out.println("not equal");
		}
		
		set.add("Ten"); // Updating the first set
		
		if(set.equals(set2)) {
			System.out.println("equal");
		}else {
			System.out.println("not equal");
		}
		
	}	
}

Output:

[One, Seven, Three, Two]
[One, Seven, Three, Two]
equal
not equal

Finding elements in TreeSet

Searching for elements in a TreeSet is done using the contains() method. This method takes a single argument, which is the element that you want to search for in the TreeSet. This method returns a boolean value, which is true if the element is found in the TreeSet and false if the element is not found.

Similarly, we can use isEmpty() method to check if the tree set is empty or not.

package javaexample;

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

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a TreeSet
		Set<String> set = new TreeSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// Finding element
		String el = "Ten";
		boolean result = set.contains(el);
		if(result) {
			System.out.println(el+" is present in the set");
		} else System.out.println(el+" is not present in the set");
 		
		result = set.isEmpty(); // check if set is empty
		if(result) {
			System.out.println("set is empty");
		} else System.out.println("set is not empty");
	}	
}

Output:

[One, Seven, Three, Two]
Ten is not present in the set
set is not empty

Create a Spliterator in TreeSet

In Java, a Spliterator (short for “Splittable Iterator”) is a class that allows for the efficient traversal and partitioning of elements in a collection, such as a List or Set. It is similar to an Iterator, but it can also be split into multiple independent iterators that can be used to traverse the same data in parallel.

We can get Spliterator from a TreeSet by using its spliterator() method. See the below code example.

package javaexample;

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

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a TreeSet
		Set<String> set = new TreeSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// Spliterator
		Spliterator<String> spl = set.spliterator();
		
		// Traverse elements
		spl.forEachRemaining(System.out::println);
		
	}	
}

Output:

[One, Seven, Three, Two]
One
Seven
Three
Two

TreeSet Methods

Java TreeSet class provides several methods for searching, adding, and removing elements, making it a versatile data structure for various applications. Its built-in methods are listed below.

Method Description
public Iterator<E> iterator() It returns an iterator over the elements in this set.
public Iterator<E> descendingIterator() It returns an iterator over the elements in descending order.
public NavigableSet<E> descendingSet() It returns a reverse order view of the elements contained in this set
public int size() It returns the number of elements in the set.
public boolean isEmpty() It returns true if this set contains no elements.
public boolean contains​(Object o) It returns true if this set contains the specified element.
public boolean add​(E e) It adds the specified element to this set if it is not already present.
public boolean remove​(Object o) It removes the specified element from this set.
public void clear() It removes all of the elements from this set.
public boolean addAll​(Collection<? extends E> c) It adds all of the elements in the specified collection to this set.
public NavigableSet<E> subSet​(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) It returns a view of the portion of this set whose elements range from fromElement to toElement.
public NavigableSet<E> headSet​(E toElement, boolean inclusive) It returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement.
public NavigableSet<E> tailSet​(E fromElement, boolean inclusive) It returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.
public SortedSet<E> subSet​(E fromElement, E toElement) It returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
public SortedSet<E> headSet​(E toElement) It returns a view of the portion of this set whose elements are strictly less than toElement.
public SortedSet<E> tailSet​(E fromElement) It returns a view of the portion of this set whose elements are greater than or equal to fromElement.
public E first() It returns the first (lowest) element currently in this set.
public E last() It returns the last (highest) element currently in this set.
public E lower​(E e) It returns the greatest element in this set strictly less than the given element, or null if there is no such element.
public E floor​(E e) It returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
public E ceiling​(E e) It returns the least element in this set greater than or equal to the given element, or null if there is no such element.
public E higher​(E e) It returns the least element in this set strictly greater than the given element, or null if there is no such element.
public E pollFirst() It retrieves and removes the first (lowest) element, or returns null if this set is empty.
public E pollLast() It retrieves and removes the last (highest) element, or returns null if this set is empty.
public Object clone() It returns a shallow copy of this TreeSet instance. (The elements themselves are not cloned.)
public Spliterator<E> spliterator() It creates a late-binding and fail-fast Spliterator over the elements in this set.

HashSet vs TreeSet

The TreeSet class is similar to the HashSet class, which is another class in the Java Collection Framework. Both classes are used to store unique elements, but there are some key differences between the two.

The main difference between TreeSet and HashSet is the way they store and order elements. The HashSet class stores elements in a hash table, which provides efficient operations for adding and removing elements. However, the HashSet class does not guarantee that the elements will be in any particular order. On the other hand, the TreeSet class stores elements in a red-black tree, which provides efficient operations.

Conclusion

TreeSet class is useful when we want to store elements in sorted order. By nature, Set stores elements in unsorted order and if we want to get sorted one then TreeSet is a good option. It provides several built-in methods to perform operations on it.

Leave a Reply

Your email address will not be published. Required fields are marked *