TreeSet in Java implements the Set interface and is based on the tree data structure. It is similar to HashSet except that it sorts the data in ascending order. We will see more differences between TreeSet and HashSet towards the end of this tutorial.
Table of Contents
Java TreeSet
Java TreeSet stores only unique elements and does not allow to store null values. It internally maintains ascending order like a TreeMap. TreeSet is very useful to store large data since access and retrieval time is faster than other collection classes. It implements the SortedSet interface internally due to which it sorts the elements in ascending order by default.
Java TreeSet Constructors
Below are the constructors that we can use while creating a TreeSet in Java.
Constructor | Description |
---|---|
TreeSet() | Creates an empty TreeSet and sorts the data in ascending order |
TreeSet(Collection c) | Creates a TreeSet that contains elements in the Collection c |
TreeSet(Comparator comp) | Creates an empty TreeSet that sorts the elements based on the specified comparator |
TreeSet(SortedSet s) | Creates a TreeSet that contains elements in the SortedSet s. |
TreeSet Methods
Below are the methods that we can use with a Java TreeSet class.
Method | Description | Parameters |
---|---|---|
boolean add(Object e) | Adds the specified element to the set | e - The element to be added Returns true if the element is not present already Returns false if element is already present |
boolean addAll(Collection c) | Adds all the elements in the specified collection | c - collection that contains elements to add |
Object ceiling(Object e) | Returns the last element in the set which is greater than or equal to the specified element | e - element in the set Returns false if there is no such element to return |
void clear() | Removes all the elements in the set and makes the set empty | |
Object clone() | Returns a shallow copy of the TreeSet instance | |
Comparator comparator() | Returns the comparator used to sort the elements in the set | |
boolean contains(Object o) | Returns true if the set contains the specified element | o - the element to search |
boolean containsAll(Collection c) | Returns true if the set contains all elements specified in the collection | c - collection elements to search |
Iterator descendingIterator() | Returns an iterator over the elements in the set in descending order | |
NavigableSet descendingSet() | Returns a reverse order view of the elements in the set | |
boolean equals(Object o) | Compares the specified object in the set | Returns true if present Returns false if not present |
Object first() | Returns the first(lowest) element in the set | |
Object floor(Object e) | Returns the greatest element in the set which is less than or equal to the specified element | e - element to compare |
SortedSet headSet(Object toElement) | Returns a view of the portion of the elements that is strictly less than the specified element | toElement -end point of the element(exclusive) |
NavigableSet headSet(Object toElement, boolean toinclusive) | Returns a view of the portion of the elements that is strictly less than or equal to the specified element | toElement -end point of the element toinclusive - if true, includes the element, if false, excludes the element |
Object higher(Object e) | Returns the element that is greater than the specified element | e - element to match |
boolean isEmpty() | Returns true if the set is empty and does not contain any elements | |
Iterator iterator() | Returns an iterator over the elements in the ascending order | |
Object last() | Returns the last or highest element in the set | |
Object lower(Object e) | Returns the greatest element that is less than the specified element | e - element to match |
Object pollFirst() | Retrieves and removes the first element in the set | |
Object pollLast() | Retrieves and removes the last element in the set | |
boolean remove(Object o) | Removes the specified element from the set | o - the element to be removed |
boolean removeAll(Collection c) | Removes all the elements in the specified collection | c - the collection of elements to be removed |
boolean retainAll(Collection c) | Retains all the elements in the specified collection in the set and removes the other elements in the Set | c - the collection of elements to be retained |
int size() | Returns the size of the set that is the number of elements in the set | |
Spliterator spliterator() | Returns the spliterator over the elements in the set | |
SortedSet subset(Object fromElement, Object toElement) | Returns a view of the portion of the elements in the set ranging from the fromElement(inclusive) until the toElement(exclusive) | fromElement - start element toElement - end element |
NavigableSet subSet(Object fromElement, boolean fromInclusive, Object toElement, boolean toInclusive) | Returns a view of the portion of the elements in the set ranging from the fromElement until the toElement | fromElement - start element toElement - end element fromInclusive - if true includes the element toInclusive - if true includes the end element |
SortedSet tailSet(Object fromElement) | Returns a view of the portion of the elements in the set that is greater than the specified element | fromElement - start element |
NavigableSet tailSet(Object fromElement, boolean fromInclusive) | Returns a view of the portion of the elements in the set that is greater than or equal to the specified element | fromElement - start element fromInclusive - if true includes the start element |
Object[] toArray() | Returns an array representation of the elements in the set | |
String toString() | Returns a string representation of the elements in the set |
Example: Add elements to the TreeSet in Java
Below is an example to add elements to TreeSet in Java using the add()
and addAll()
methods.
import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet<String> ts = new TreeSet<String>(); ts.add("Bangalore"); ts.add("Chennai"); ts.add("Delhi"); System.out.println("Eleemnts in the TreeSet after add operation:" + ts); TreeSet<String> t = new TreeSet<String>(); t.add("Mumbai"); t.add("Hyderabad"); ts.addAll(t); System.out.println("Elements in the TreeSet after addAll operation: " + ts); } }
Eleemnts in the TreeSet after add operation:[Bangalore, Chennai, Delhi] Elements in the TreeSet after addAll operation: [Bangalore, Chennai, Delhi, Hyderabad, Mumbai]
Example: Remove elements from TreeSet
In the below example, we use the remove()
method to remove the specified element from the Java TreeSet and removeAll()
method to remove all the elements in the specified collection from the TreeSet.
import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet<String> ts = new TreeSet<String>(); ts.add("Bangalore"); ts.add("Chennai"); ts.add("Delhi"); ts.add("Goa"); ts.add("Mysore"); System.out.println("Elements in the TreeSet after add operation:" + ts); ts.remove("Chennai"); System.out.println("Elements in the TreeSet after remove method: " + ts); TreeSet<String> t = new TreeSet<String>(); t.add("Mumbai"); t.add("Hyderabad"); ts.addAll(t); System.out.println("Elements in the TreeSet after addAll operation: " + ts); ts.removeAll(t); System.out.println("Elements in the TreeSet after removeAll method: " + ts); ts.pollFirst(); System.out.println("Elements in the TreeSet after pollFirst method: " + ts); ts.pollLast(); System.out.println("Elements in the TreeSet after pollLast method: " + ts); } }
Elements in the TreeSet after add operation:[Bangalore, Chennai, Delhi, Goa, Mysore] Elements in the TreeSet after remove method: [Bangalore, Delhi, Goa, Mysore] Elements in the TreeSet after addAll operation: [Bangalore, Delhi, Goa, Hyderabad, Mumbai, Mysore] Elements in the TreeSet after removeAll method: [Bangalore, Delhi, Goa, Mysore] Elements in the TreeSet after pollFirst method: [Delhi, Goa, Mysore] Elements in the TreeSet after pollLast method: [Delhi, Goa]
Example: Retain elements in the TreeSet
Below is the example to demonstrate the retainAll()
method which retains the elements in the collection and removes other elements from the TreeSet.
import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet<String> ts = new TreeSet<String>(); ts.add("Bangalore"); ts.add("Chennai"); ts.add("Delhi"); System.out.println("Elements in the TreeSet after add operation:" + ts); TreeSet<String> t = new TreeSet<String>(); t.add("Mumbai"); t.add("Hyderabad"); ts.addAll(t); System.out.println("Elements in the TreeSet after addAll operation: " + ts); ts.retainAll(t); System.out.println("Elements in the TreeSet after retainAll operation: " + ts); } }
Elements in the TreeSet after add operation:[Bangalore, Chennai, Delhi] Elements in the TreeSet after addAll operation: [Bangalore, Chennai, Delhi, Hyderabad, Mumbai] Elements in the TreeSet after retainAll operation: [Hyderabad, Mumbai]
Example: Check element exists and retrieve elements
We can check if an element exists in the Java TreeSet using the contains()
method and check a collection of elements using the containsAll()
method. We can retrieve the first value using the first()
method and the last value using the last()
method. The ceiling()
, floor()
, the lower()
and higher()
methods retrieve the values based on the specified value.
import java.util.TreeSet; public class RetrieveElementsTreeSet { public static void main(String[] args) { TreeSet<String> ts = new TreeSet<String>(); ts.add("Bangalore"); ts.add("Chennai"); ts.add("Delhi"); ts.add("Goa"); ts.add("Mysore"); TreeSet<String> t = new TreeSet<String>(); t.add("Mumbai"); t.add("Hyderabad"); ts.addAll(t); System.out.println("Elements in the TreeSet: " + ts); System.out.println("Contains Goa: " + ts.contains("Goa")); System.out.println("Contains Pune: " + ts.contains("Pune")); System.out.println("Contains collection elements: " + ts.containsAll(ts)); System.out.println("Ceiling output: " + ts.ceiling("Delhi")); System.out.println("Floor output: " + ts.floor("Delhi")); System.out.println("First element: " + ts.first()); System.out.println("Last element: " + ts.last()); System.out.println("Lower element: " + ts.lower("Delhi")); System.out.println("Higher element: " + ts.higher("Delhi")); } }
Elements in the TreeSet: [Bangalore, Chennai, Delhi, Goa, Hyderabad, Mumbai, Mysore] Contains Goa: true Contains Pune: false Contains collection elements: true Ceiling output: Delhi Floor output: Delhi First element: Bangalore Last element: Mysore Lower element: Chennai Higher element: Goa
Example: Iterate through elements in a TreeSet
The below example shows how to iterate through values in a TreeSet. By using an iterator, it sorts the elements in the ascending order. To sort the elements in the reverse order, we can use either descendingIterator()
or descendingSet()
method.
import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class IterateTreeSet { public static void main(String[] args) { TreeSet<String> ts = new TreeSet<String>(); ts.add("Bangalore"); ts.add("Delhi"); ts.add("Mysore"); ts.add("Goa"); ts.add("Chennai"); System.out.println("Iterate using iterator:"); Iterator<String> it = ts.iterator(); while(it.hasNext()) System.out.println(it.next()); System.out.println("Iterate reverse using descendingIterator:"); Iterator<String> di = ts.descendingIterator(); while(di.hasNext()) System.out.println(di.next()); System.out.println("Iterate reverse using descendingSet:"); Set<String> s = ts.descendingSet(); s.forEach(System.out::println); } }
Iterate using iterator: Bangalore Chennai Delhi Goa Mysore Iterate reverse using descendingIterator: Mysore Goa Delhi Chennai Bangalore Iterate reverse using descendingSet: Mysore Goa Delhi Chennai Bangalore
Example: headSet, tailSet, and subSet methods in a TreeSet
The below example shows how to retrieve a portion of the data in the TreeSet. The headSet()
method returns all the data from the start until the element specified. The tailSet()
method returns all the data from the specified element until the end. Using the subSet()
method, we can retrieve a range of values based on the elements specified.
import java.util.TreeSet; public class TreeSetMethods { public static void main(String[] args) { TreeSet<Integer> ts = new TreeSet<Integer>(); ts.add(50); ts.add(10); ts.add(80); ts.add(30); ts.add(20); System.out.println("Elements in a TreeSet: " + ts.toString()); System.out.println("HeadSet:"); System.out.println(ts.headSet(30)); System.out.println(ts.headSet(30, true)); System.out.println(ts.headSet(30, false)); System.out.println("TailSet:"); System.out.println(ts.tailSet(30)); System.out.println(ts.tailSet(30, true)); System.out.println(ts.tailSet(30, false)); System.out.println("SubSet:"); System.out.println(ts.subSet(20, 50)); System.out.println(ts.subSet(20, true, 50, true)); System.out.println(ts.subSet(20, true, 50, false)); System.out.println(ts.subSet(20, false, 50, true)); System.out.println(ts.subSet(20, false, 50, false)); } }
Elements in a TreeSet: [10, 20, 30, 50, 80] HeadSet: [10, 20] [10, 20, 30] [10, 20] TailSet: [30, 50, 80] [30, 50, 80] [50, 80] SubSet: [20, 30] [20, 30, 50] [20, 30] [30, 50] [30]
Difference between TreeSet and HashSet
TreeSet | HashSet |
---|---|
Maintains ascending order | Does not maintain any order |
Computation is slower | Computation is faster |
Time cost is log(n) | Time cost is constant |