Updated April 1, 2023
Introduction to TreeSet in Java
TreeSet in Java is considered to be one of the main implementations of the interface SortedSet that helps in storage. In this, elements are ordered in such a way that they are set in natural ordering or order based on an explicit comparator. TreeSet is inheriting the class AbstractSet and implements the interface NavigableSet. Even though it is similar to HashSet, it maintains an ordering while the HashSet does not maintain it. Moreover, null elements are allowed by TreeSet, unlike HashSet. More details on TreeSet will be discussed in the following sections.
Features of TreeSet
Below are the main features of TreeSet.
- Duplicate values are not permitted.
- Objects are sorted based on ascending order.
- The insertion order is not preserved. In addition to that, elements are sorted based on the keys.
- Heterogeneous objects are not permitted to insert. If we try to insert, classCastException will be thrown during runtime.
- Store a huge amount of sorted data.
- Fast Retrieval time.
- Fast Access.
- Null elements are not allowed.
- Operations such as add, search and remove take the time of O(log n).
- In the case of operations such as printing of n number of elements, the time complexity of O(n) will be present.
- Non synchronized.
- The presence of TreeMap is there to store elements.
- Not Thread-safe.
Syntax:
In order to create a TreeSet, first import the package java.util.TreeSet. After that, create a TreeSet using the syntax:
TreeSet<Integer> num= new TreeSet<>();
Since we have created TreeSet without mentioning any arguments, elements will be sorted in their natural ordering. i.e. Ascending order.
As already mentioned, sorting can be customized by using the interface Comparator.
Constructors of TreeSet in Java
TreeSet in Java has 4 constructors. They are:
- TreeSet(): A new and empty TreeSet will be created with sorting based on the natural ordering.
- TreeSet(Collection<? extends E> c): A new TreeSet will be created with elements mentioned in the collection c and they will be sorted based on the natural ordering.
- TreeSet(Comparator<? super E> comparator): A new and empty TreeSet will be created with sorting based on the mentioned comparator.
- TreeSet(SortedSet<E> s): A new TreeSet will be created with elements mentioned in the sortedset s with ordering the same as that of it.
Methods of TreeSet in Java
There are several functions that need to be performed in TreeSet. Let us see what they are.
- add(Ee): An element e will be added to the set if it is not present in it.
- addAll(Collection<? extends E> c): All the elements in collection c will be added to the set.
- E ceiling(Ee): The last element which is greater than or equal to the element in the set will be returned.
- clear(): All the elements in the set will be removed.
- clone(): A shallow copy will be returned for the TreeSet instance.
- comparator(): The comparator used in the set will be returned. If natural ordering is used, null will be returned.
- contains(Objecto): If the set contains the element o, true will be returned.
- descendingIterator(): An iterator will be returned over the elements in descending order.
- descendingSet(): A reverse order view will be returned for the elements present in the list.
- first(): he first or the lowest element in the set will be returned.
- last(): The last or the largest element in the set will be returned.
- iterator(): n iterator will be returned over the elements in ascending order.
- lower(Ee): The greatest element will be returned which is strictly small than the element e which is given. If there is no such element, null will be returned.
- higher(Ee): The smallest element will be returned which is strictly high than the element e which is given. If there is no such element, null will be returned.
- isEmpty(): True will be returned if no elements are present.
- size(): The number of elements in the set will be returned. In other words, cardinality will be returned.
- pollFirst(): The first or the lowest element in the set will be retrieved and removed. If there are no elements in the set, the null will be returned.
- pollLast(): The last or the highest element in the set will be retrieved and removed. If there are no elements in the set, the null will be returned.
- remove(Objecto): If the set contains the element o, it will be removed.
- subSet(EfromElement, boolean fromInclusive, E toElement, boolean toInclusive): A view will be returned for the portion of the set from the range from Element to toElement.
- subSet(EfromElement, E toElement): A view will be returned for the portion of the set from the range fromElement(inclusive) to toElement(exclusive).
- tailSet(EfromElement): view will be returned for the portion of the set where elements are larger than fromElement.
- tailSet(EfromElement, boolean inclusive): A view will be returned for the portion of the set where elements are larger than fromElement. It is considered if inclusive is true.
Example of TreeSet in Java
Java program to create a tree set with the natural ordering of elements.
import java.util.SortedSet;
import java.util.TreeSet;
//class
public class TreeSetExample {
//main method
public static void main(String[] args) {
// TreeSet fam creation
SortedSet<String> fam = new TreeSet<>();
// Adding new elements to a TreeSet
fam.add("Anna");
fam.add("Adam");
fam.add("Sam");
fam.add("Iza");
//print the treeset
System.out.println("Fam Set : " + fam);
// Trying to add duplicate element Anna
fam.add("Anna");
System.out.println("Added element Anna, Now the treeset is : " + fam);
// Trying to add element Anna with lower case
fam.add("anna");
System.out.println("Added element anna, Now the treeset is : " + fam);
}
}
Output:
A treeset fam is created first. Once it is created, elements are added to it and the whole treeset is printed. After this, an element ‘Anna’ which is already present in the treeset is trying to get added. Since duplicates are not allowed in TreeSet, it is not get added. After that, an element ‘anna’ which is the lower case of the already existing element ‘Anna’ is added. Since it is in lowercase, it gets added to the treeset without any problem.
Conclusion
TreeSet in Java is an implementation of the interface SortedSet that helps in storage where the elements are arranged in natural ordering or based on the comparator. Several aspects of TreeSet is discussed in this document.
Recommended Articles
This is a guide to TreeSet in Java. Here we discuss the Main Features along with the Constructors and Methods of TreeSet in Java. You may also look at the following articles to learn more –