Java TreeSet Class
The TreeSet class is a part of java collection framework. It is available inside the java.util package. The TreeSet class extends AbstractSet class and implements NavigableSet, Cloneable, and Serializable interfaces.
The elements of TreeSet are organized using a mechanism called tree. The TreeSet class internally uses a TreeMap to store elements. The elements in a TreeSet are sorted according to their natural ordering.
🔔 The TreeSet is a child class of AbstractSet
🔔 The TreeSet implements interfaces like NavigableSet, Cloneable, and Serializable.
🔔 The TreeSet does not allows to store duplicate data values, but null values are allowed.
🔔 The elements in a TreeSet are sorted according to their natural ordering.
🔔 The TreeSet initial capacity is 16 elements.
🔔 The TreeSet is best suitable for search operations.
TreeSet class declaration
The TreeSet class has the following declaration.
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
TreeSet class constructors
The TreeSet class has the following constructors.
- TreeSet( ) - Creates an empty TreeSet in which elements will get stored in default natural sorting order.
- TreeSet(Collection c) - Creates a TreeSet with given collection of elements.
- TreeSet(Comparator c) - Creates an empty TreeSet with the specified sorting order.
- TreeSet(SortedSet s) - This constructor is used to convert SortedSet to TreeSet.
Operations on TreeSet
The TreeSet class allow us to perform several operations like adding, accesing, deleting, updating, looping, etc. Let's look at each operation with examples.
Adding Items
The TreeSet class has the following methods to add items.
- boolean add(E element) - Inserts given element to the TreeSet if it does not exist.
- boolean addAll(Collection c) - Inserts given collection of elements to the TreeSet.
Let's consider an example program to illustrate adding items to the TreeSet.
import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet set = new TreeSet();
TreeSet anotherSet = new TreeSet();
set.add(10);
set.add(20);
set.add(15);
set.add(5);
System.out.println("\nset is\n" + set);
anotherSet.addAll(set);
System.out.println("\nanotherSet is\n" + anotherSet);
}
}
Accessing Items
The TreeSet class has provides the following methods to access items.
- 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 does not found returns null.
- E lower(E obj) - Returns the largest element e such that e<obj. If it does not found returns null.
- E ceiling(E obj) - Returns the smallest element e such that e>=obj. If it does not found returns null.
- E floor(E obj) - Returns the largest element e such that e<=obj. If it does not found 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.
Let's consider an example program to illustrate accessing items from a TreeSet.
import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet set = new TreeSet();
Random num = new Random();
for(int i = 0; i < 10; i++)
set.add(num.nextInt(100));
System.out.println("\nset is\n" + set);
System.out.println("\nfirst() - " + set.first());
System.out.println("\nlast() - " + set.last());
System.out.println("\nhigher(20) - " + set.higher(20));
System.out.println("\nlower(20) - " + set.lower(20));
System.out.println("\nceiling(30) - " + set.ceiling(30));
System.out.println("\nfloor(30) - " + set.floor(30));
System.out.println("\nsubSet(10, 50)\n" + set.subSet(10, 50));
System.out.println("\nsubSet(10, false, 50, true)\n" + set.subSet(10, false, 50, true));
System.out.println("\nheadSet(20)\n" + set.headSet(20));
System.out.println("\nheadSet(20, false)\n" + set.headSet(20, false));
System.out.println("\ntailSet(20)\n" + set.tailSet(20));
System.out.println("\ntailSet(20, false)\n" + set.tailSet(20, false));
}
}
Updating Items
The TreeSet class has no methods to update or change items.
Removing Items
The TreeSet class has the following methods to remove items.
- boolean remove(Object o) - Removes the specified element from the invoking TreeSet.
- boolean removeAll(Collection c) - Removes all the elements those 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.
- E pollFirst( ) - Removes the first (smallest) element from the invoking TreeSet, and returns the same.
- E pollLast( ) - Removes the last (largest) element from the invoking TreeSet, and returns the same.
- void clear( ) - Removes all the elements from the TreeSet.
Let's consider an example program to illustrate removing items from the TreeSet.
import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet set = new TreeSet();
TreeSet anotherSet = new TreeSet();
Random num = new Random();
for(int i = 0; i < 10; i++)
set.add(num.nextInt(100));
anotherSet.add(10);
anotherSet.add(20);
anotherSet.add(30);
System.out.println("\nset is\n" + set);
System.out.println("\nanotherSet is\n" + anotherSet);
set.remove(50);
System.out.println("\nset after remove(50) is\n" + set);
set.removeIf(n->n.equals(60));
System.out.println("\nset after removeIf(n->n.equals(60)) is\n" + set);
set.pollFirst();
System.out.println("\nset after pollFirst( ) is\n" + set);
set.pollLast();
System.out.println("\nset after pollLast( ) is\n" + set);
set.removeAll(anotherSet);
System.out.println("\nset after removeAll(anotherSet) is\n" + set);
set.retainAll(anotherSet);
System.out.println("\nset after retainAll(anotherSet) is\n" + set);
}
}
Other utility methods
The TreeSet class has the following methods to work with elements of it.
- int size( ) - Returns the total number of elements in the invoking TreeSet.
- boolean isEmpty( ) - Returns true if the TreeSet is empty otherwise returns false.
- TreeSet clone( ) - Returns a copy of the invoking TreeSet.
- boolean contains(Object element) - Returns true if the TreeSet contains given element otherwise returns false.
- boolean containsAll(Collection c) - Returns true if the TreeSet contains given collection of elements otherwise returns false.
- boolean equals(Object o) - Compares the specified object with invoking TreeSet collection for equality.
- int hashCode( ) - Returns the hash code of the invoking TreeSet.
- Object clone( ) - Returns a shallow copy of invoking TreeSet instance.
- Spliterator spliterator( ) - Creates 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.
Let's consider an example program to illustrate other utility methods of the TreeSet.
import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet set = new TreeSet();
TreeSet anotherSet = new TreeSet();
Random num = new Random();
for(int i = 0; i < 10; i++)
set.add(num.nextInt(100));
anotherSet.add(10);
anotherSet.add(20);
anotherSet.add(30);
System.out.println("\nset is\n" + set);
System.out.println("\nanotherSet is\n" + anotherSet);
System.out.println("\nset size() - " + set.size());
System.out.println("\nset isEmpty() - " + set.isEmpty());
System.out.println("\nset contains(50) - " + set.contains(50));
System.out.println("\nset contains(anotherSet) - " + set.containsAll(anotherSet));
System.out.println("\nset equals(anotherSet) - " + set.equals(anotherSet));
System.out.println("\nset hashCode() - " + set.hashCode());
}
}
Consolidated list of methods
The following table providess a consolidated view of all methods of TreeSet.
Method | Description |
---|---|
boolean add(E element) | Appends 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 does not found returns null. |
E lower(E obj) | Returns the largest element e such that e<obj. If it does not found returns null. |
E ceiling(E obj) | Returns the smallest element e such that e>=obj. If it does not found returns null. |
E floor(E obj) | Returns the largest element e such that e<=obj. If it does not found 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 occurence of the given element from the invoking TreeSet. |
boolean removeAll(Collection c) | Removes all the elements those 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 returns false. |
boolean equals( ) | Compares the specified object with invoking TreeSet collection for equality. |
boolean contains(Object element) | Returns true if the HashSet contains given element otherwise returns false. |
boolean containsAll(Collection c) | Returns true if the TreeSet contains all elements of given collection otherwise returns false. |
int clone( ) | Returns a copy of the invoking TreeSet. |
int hashCode( ) | Returns the hash code of the invoking TreeSet. |
Spliterator spliterator( ) | Creates 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. |