Last Updated: 03 October, 2023
The TreeSet class of the Java collections framework was introduced in the JDK 1.2 version and is available in the java.util package.
A TreeSet is a sorted collection of objects. A TreeSet is the implementation of the SortedSet interface in Java that uses a tree for storage. The ordering of the elements is maintained by a set using their natural (ascending) order.
TreeSet provides fast access and retrieval operations, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.
As we can see from the complete hierarchy above, TreeSet extends the AbstractSet class and implements the NavigableSet interface as well as the Serializable and Cloneable interfaces.
Here, E defines the type of elements that the Set will contain.
Output
[10, 20, 30, 40, 50]
The Java TreeSet class has the following constructors:
Constructor Name and Descriptions |
---|
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. |
The Java TreeSet class has the following methods:
Method | Description |
---|---|
boolean add(E element) | Appends the given element to the TreeSet. |
boolean addAll(Collection c) | Appends given collection of elements to the TreeSet. |
E First() | Returns the first (smallest) element from the invoking TreeSet. |
E last() | Returns the last (largest) element from the invoking TreeSet. |
E higher(E obj) | Returns the largest element e such that e>obj. If it is not found, it returns null. |
E lower(E obj) | Returns the largest element e such that e<obj. If it is not found, it returns null. |
E ceiling(E obj) | Returns the smallest element e such that e>=obj. If it is not found, it returns null. |
E floor(E obj) | Returns the largest element e such that e<=obj. If it is not found, it returns null. |
SortedSet subSet(E fromElement, E toElement) | Returns a set of elements that lie between the given range, which includes fromElement and excludes toElement. |
NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) | Returns a set of elements that lie between the given range from the invoking TreeSet. |
SortedSet tailSet(E fromElement) | Returns a set of elements that are greater than or equal to the specified fromElement from the invoking TreeSet. |
NavigableSet tailSet(E fromElement, boolean inclusive) | Returns a set of elements that are greater than or equal to (if inclusive is true) the specified element from the invoking TreeSet. |
SortedSet headSet(E fromElement) | Returns a set of elements that are smaller than or equal to the specified fromElement from the invoking TreeSet. |
NavigableSet headSet(E fromElement, boolean inclusive) | Returns a set of elements that are smaller than or equal to (if inclusive is true) the specified element from the invoking TreeSet. |
boolean remove(Object element) | Removes the first occurrence of the given element from the invoking TreeSet. |
boolean removeAll(Collection c) | Removes all the elements that are in the specified collection from the invoking TreeSet. |
boolean removeIf(Predicate p) | Removes all of the elements of the TreeSet collection that satisfy the given predicate. |
boolean retainAll(Collection c) | Removes all the elements except those are in the specified collection from the invoking TreeSet. |
void clear() | Removes all the elements from the TreeSet. |
int size() | Returns the total number of elements in the invoking TreeSet. |
boolean isEmpty() | Returns true if the TreeSet is empty; otherwise, it returns false. |
boolean equals() | Compares the specified object with an invoking TreeSet collection for equality. |
boolean contains(Object element) | Returns true if the HashSet contains the given element; otherwise, it returns false. |
boolean containsAll(Collection c) | Returns true if the TreeSet contains all elements of the given collection; otherwise, it returns false. |
int clone() | Returns a copy of the invoking TreeSet. |
int hashCode() | Returns the hash code of the invoking TreeSet. |
Spliterator spliterator() | Creates a spliterator over the elements in a TreeSet. |
Iterator iterator() | Returns an iterator over the elements in the TreeSet. The iterator does not return the elements in any particular order. |
The Java TreeSet class provided methods are implemented in the below given examples. Let's go through the examples one by one and understand the uses for each method.
Example 1 : Methods for Adding elements in TreeSet
Output
TreeSet elements: [200, 400, 500, 800]
TreeSet elements after adding another TreeSet
[10, 20, 30, 40, 200, 400, 500, 800]
Example 2 : Methods for Accessing elements from TreeSet
Output
TreeSet elements: [10, 20, 30, 40, 50, 60, 80]
treeSet.ceiling(30) : 30
treeSet.floor(40) : 40
treeSet.pollFirst() : 10
treeSet.pollLast() : 80
treeSet.descendingSet() : [60, 50, 40, 30, 20]
treeSet.first() : 20
treeSet.last() : 60
Example 3 : Methods for Removing elements from TreeSet
Output
TreeSet elements: [10, 20, 30, 40, 50, 60, 70]
After calling remove() method: [10, 20, 30, 50, 60, 70]
After calling removeAll() method: [10, 30, 50]
After calling removeIf() method: [30, 50]
After calling retainingAll() method: []
Before calling clear() method: [20, 60, 70]
After calling clear() method: []
Example 4 : Utility methods of TreeSet
Output
TreeSet elements: [10, 20, 30, 40, 50, 70, 80]
TreeSet Size: 7
Is TreeSet Empty: false
TreeSet contains() method: true
TreeSet containsAll() method: false
ArrayList elements: [10, 20, 30, 40, 50, 70, 80]
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TreeSet.html
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
What is the difference between LinkedHashSet and TreeSet in Java?
Ans. LinkedHashSet and TreeSet both implement the Set interface. Both have many differences. Let's understand with the help of the given table.
LinkedHashSet | TreeSet |
---|---|
The underlying data structure is a hash table + linked list (doubly linked list). | The underlying data structure of the TreeSet is the Balanced Tree. |
Preserve the iteration order (ordered set). | Store the elements in a sorted order (default, in ascending order). |
Introduced in the JDK 1.4 version. | Introduced in the JDK 1.2 version. |
Allows to insert a null value. | Does not allow to insert a null. |
How to convert a HashSet into TreeSet in Java?
Ans. To convert HashSet into TreeSet, we create a TreeSet and pass the HashSet object as a constructor parameter in the TreeSet. See the example below.
import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class ConvertHashSetInToTreeSet { public static void main(String[] args) { // Creating a HashSet HashSet<Integer> hashSet = new HashSet<>(); // Adding values in HashSet hashSet.add(400); hashSet.add(300); hashSet.add(200); System.out.println("HashSet Values are : " + hashSet); // Creating a TreeSet // Passing hashSet object as a constructor parameter Set<Integer> treeSet = new TreeSet<>(hashSet); System.out.println("TreeSet values are : " + treeSet); } }
Output
HashSet Values are : [400, 200, 300]
TreeSet values are : [200, 300, 400]