English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about the Java TreeSet class and its various operations and methods through examples.
The TreeSet class in the Java collection framework provides the functionality of a tree data structure.
It extendsNavigableSet interface
To create a TreeSet, we must first import the java.util.TreeSet package.
After importing the package, here's how to create a TreeSet in Java.
TreeSet<Integer> numbers = new TreeSet<>();
Here, we create a TreeSet with no parameters. In this example, the elements in the TreeSet are naturally sorted (in ascending order).
However, we can use the Comparator interface to customize the sorting of elements. We will learn about it in the later part of this tutorial.
The TreeSet class provides various methods that allow us to perform various operations on the collection.
add() - Insert the specified element into the collection
addAll() - Insert all elements of the specified collection into the collection
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> evenNumbers = new TreeSet<>(); // Using the add() method evenNumbers.add(2); evenNumbers.add(4); evenNumbers.add(6); System.out.println("TreeSet: " + evenNumbers) TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(1); // Using the addAll() method numbers.addAll(evenNumbers); System.out.println("new TreeSet: " + numbers) } }
Output Result
TreeSet: [2, 4, 6] new TreeSet: [1, 2, 4, 6]
To access the elements of TreeSet, we can use the iterator() method. To use this method, we must import the java.util.Iterator package. For example,
import java.util.TreeSet; import java.util.Iterator; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(6); System.out.println("TreeSet: " + numbers) // Call the iterator() method Iterator<Integer> iterate = numbers.iterator(); System.out.print("TreeSet uses iterator: "); //Access element while(iterate.hasNext()) { System.out.print(iterate.next()); System.out.print(", "); } } }
Output Result
TreeSet: [2, 5, 6] TreeSet uses iterator: 2, 5, 6,
remove() - Remove the specified element from the collection
removeAll() - Remove all elements from the collection
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(6); System.out.println("TreeSet: " + numbers) // Using the remove() method boolean value1 value = numbers.remove("5); System.out.println(""5Were they deleted? " + value1); // Using the removeAll() method boolean value2 value = numbers.removeAll(numbers); System.out.println("Did all elements get deleted? ") + value2); } }
Output Result
TreeSet: [2, 5, 6] 5Were they deleted? true Did all elements get deleted? true
Because TreeSet class implements NavigableSet, it provides various methods to navigate through the elements of the set.
first() - Returns the first element of the collection
last() - Returns the last element of the collection
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(6); System.out.println("TreeSet: " + numbers) // Using the first() method int first = numbers.first(); System.out.println("The first number: " ) + first); // Use the last() method int last = numbers.last(); System.out.println("The last number: " + last); } }
Output Result
TreeSet: [2, 5, 6] The first number: 2 The last number: 6
Higher(element) - Return the smallest element greater than the specified element (element).
lower(element) - Return the largest element less than the specified element (element).
ceiling(element) - Return the smallest element greater than the specified element (element). If the specified element (element) exists in the TreeSet, then return the element (element) passed as a parameter.
floor(element) - Return the largest element less than the specified element (element). If the specified element (element) exists in the TreeSet, then return the element (element) passed as a parameter.
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers) // Use higher() System.out.println("Use higher: " + numbers.higher(4); // Use lower() System.out.println("Use lower: " + numbers.lower(4); // Use ceiling() System.out.println("Use ceiling: " + numbers.ceiling(4); // Use floor() System.out.println("Use floor: " + numbers.floor(3); } }
Output Result
TreeSet: [2, 4, 5, 6] Use higher: 5 Use lower: 2 Use ceiling: 4 Use floor: 2
pollFirst() - Return and remove the first element from the collection
pollLast() - Return and remove the last element from the collection
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers) // Use pollFirst() System.out.println("Delete the first element: " + numbers.pollFirst()); // Use pollLast() System.out.println("Delete the last element: " + numbers.pollLast()); System.out.println("new TreeSet: " + numbers) } }
Output Result
TreeSet: [2, 4, 5, 6] Delete the first element: 2 Delete the last element: 6 new TreeSet: [4, 5]
The headSet() method returns all elements before the specified element (passed as a parameter) in the specified set.
The booleanValue parameter is optional. The default value is false.
If the value of booleanValue is true, the method returns all elements before the specified element, including the specified element.
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers) // Use headSet() with the default boolean value System.out.println("Use headSet without boolean value: ", + numbers.headSet(5); // Use headSet() with specified boolean value System.out.println("Use headSet with boolean value: ", + numbers.headSet(5, true) } }
Output Result
TreeSet: [2, 4, 5, 6] Use headSet without boolean value: [2, 4] Use headSet with boolean value: [2, 4, 5]
The tailSet() method returns all elements after the specified element (passed as a parameter) in the specified set.
The booleanValue parameter is optional. The default value is true.
If false is passed as a booleanValue, the method will return all elements specified after, element, but not including the specified element.
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers) // Use tailSet() with the default boolean value System.out.println("tailSet() with the default boolean value: ", + numbers.tailSet(4); // Use tailSet() with specified boolean value System.out.println("tailSet() with boolean value: ", + numbers.tailSet(4, false)); } }
Output Result
TreeSet: [2, 4, 5, 6] Use tailSet() with the default boolean value: [4, 5, 6] tailSet() with boolean value: [5, 6]
The subSet() method returns e1and e2all elements between1
bv1and bv2is an optional parameter. bv1The default value is true, bv2The default value is false.
If false is passed as bv1Passing, the method returns e1and e2all elements between1
If true is passed as bv2Passing, the method returns e1and e2all elements between1
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers) // Use subSet() with the default boolean value System.out.println("subSet() uses the default boolean value: ", + numbers.subSet(4, 6); // Using subSet() with specified boolean value System.out.println("subSet() using specified boolean value: ") + numbers.subSet(4, false, 6, true) } }
Output Result
TreeSet: [2, 4, 5, 6] subSet() using default boolean value: [4, 5] subSet() using specified boolean value: [5, 6]
Methods of TreeSet class can also be used to perform various collection operations.
To perform the union between two collections, we use the addAll() method. For example,
import java.util.TreeSet;; class Main { public static void main(String[] args) { TreeSet<Integer> evenNumbers = new TreeSet<>(); evenNumbers.add(2); evenNumbers.add(4); System.out.println("TreeSet")1: " + evenNumbers) TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("TreeSet")2: " + numbers) //Union of two sets numbers.addAll(evenNumbers); System.out.println("Union is: ") + numbers) } }
Output Result
TreeSet1: [2, 4] TreeSet2: [1, 2, 3] Union: [1, 2, 3, 4]
To perform the intersection between two collections, we use the retainAll() method. For example,
import java.util.TreeSet;; class Main { public static void main(String[] args) { TreeSet<Integer> evenNumbers = new TreeSet<>(); evenNumbers.add(2); evenNumbers.add(4); System.out.println("TreeSet")1: " + evenNumbers) TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("TreeSet")2: " + numbers) // Intersection of two sets numbers.retainAll(evenNumbers); System.out.println("Intersection of collection: ") + numbers) } }
Output Result
TreeSet1: [2, 4] TreeSet2: [1, 2, 3] Intersection of collection: [2]
To calculate the difference between two sets, we can use the removeAll() method. For example,
import java.util.TreeSet;; class Main { public static void main(String[] args) { TreeSet<Integer> evenNumbers = new TreeSet<>(); evenNumbers.add(2); evenNumbers.add(4); System.out.println("TreeSet")1: " + evenNumbers) TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); System.out.println("TreeSet")2: " + numbers) //Difference set of collection numbers.removeAll(evenNumbers); System.out.println("Difference set: ") + numbers) } }
Output Result
TreeSet1: [2, 4] TreeSet2: [1, 2, 3, 4] Difference set: [1, 3]
To check if one collection is a subset of another, we use the containsAll() method. For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); System.out.println("TreeSet")1: " + numbers) TreeSet<Integer> primeNumbers = new TreeSet<>(); primeNumbers.add(2); primeNumbers.add(3); System.out.println("TreeSet")2: " + primeNumbers) //Check if primeNumbers is a subset of numbers boolean result = numbers.containsAll(primeNumbers); System.out.println("TreeSet")2Is TreeSet1Is it a subset? " + result); } }
Output Result
TreeSet1: [1, 2, 3, 4] TreeSet2: [2, 3] TreeSet2Is TreeSet1Is it a subset? True
Method | Description |
---|---|
clone() | Create a copy of TreeSet |
contains() | Search for the specified element in TreeSet and return a boolean result |
isEmpty() | Check if TreeSet is empty |
size() | Return the size of TreeSet |
clear() | Remove all elements from TreeSet |
Both TreeSet and HashSet implement the Set interface. However, there are some differences between them.
Unlike HashSet, the elements in TreeSet are stored in some order. This is because TreeSet also implements the SortedSet interface.
TreeSet provides some easy-to-navigate methods. For example, first(), last(), headSet(), tailSet(), etc. This is because TreeSet also implements the NavigableSet interface.
For basic operations such as add, remove, contains, and size, HashSet is faster than TreeSet.
In all the above examples, the elements of the tree set are sorted in natural order. However, we can also define the order of elements ourselves.
To do this, we need to create our own comparator class, based on sorting the elements in the tree set. For example
import java.util.TreeSet; import java.util.Comparator; class Main { public static void main(String[] args) { //Create a TreeSet using a custom comparator TreeSet<String> animals = new TreeSet<>(new CustomComparator()); animals.add("Dog"); animals.add("Zebra"); animals.add("Cat"); animals.add("Horse"); System.out.println("TreeSet: " + animals); } //Create a comparator class public static class CustomComparator implements Comparator<String> { @Override public int compare(String animal1, String animal2) { int value = animal1.compareTo(animal2); //Elements are sorted in reverse order if (value > 0) { return -1; } else if (value < 0) { return 1; } else { return 0; } } } }
Output Result
TreeSet: [Zebra, Horse, Dog, Cat]
In the above example, we create a TreeSet and pass the CustomComparator class as a parameter.
The CustomComparator class implements the Comparator interface.
Then, we rewrite the compare() method. Now, this method will sort the elements in reverse order.