Skip to content

Java TreeSet Tutorial with Examples

Java TreeSet tutorial with examples will help you understand how to use Java TreeSet in an easy way. TreeSet in Java is a Set implementation based on the TreeMap. Unlike HashMap, the elements of the TreeSet are ordered using their natural ordering. Also, unlike the Map implementations, for example, TreeMap or HashMap, the TreeSet does not maintain key value pairs but offers the uniqueness of its elements.

Java TreeSet Tutorial

If you do not want to sort the TreeSet elements using their natural ordering, you can provide a custom Comparator when you create the TreeSet object using the below given constructor.

The TreeSet in Java provides log(n) time cost for the add, remove and contains operations.

The TreeSet implementation is not synchronized. That means if multiple threads are trying to modify the TreeSet object at the same time then the access must be synchronized explicitly. If this is the case, you can either synchronize the TreeSet object or you can get the synchronized SortedSet object from the existing TreeSet using synchronizedSortedSet method of the Collections class as given below.

The Iterator object obtained by the iterator method of the TreeSet is fail-fast. That means if the TreeSet object is structurally modified after obtaining the iterator (except by using iterator’s own remove method), calling any methods of the iterator object will throw ConcurrentModificationException.

How to create a new TreeSet object?

The TreeSet class in Java provides several constructors using which we can create new TreeSet objects.

1. How to create a new empty TreeSet object?

The default constructor of the TreeSet class creates a new empty TreeSet object.

The elements added to this set will be sorted by the natural ordering of the elements.

2. How to create a new TreeSet object with a custom Comparator?

If you want to specify a custom Comparator instead of using the default natural ordering, you can do so by using the overloaded constructor with the Comparator parameter.

The elements added to this set will be ordered by the specified comparator.

Example:

Output

3. How to create a new TreeSet object from another Collection object?

The below given overridden constructor of the TreeSet class creates a new TreeSet object containing the elements from the specified Collection object.

The elements added from another collection object are sorted automatically in the natural order of the elements. The below given example shows how to create a TreeSet object from an ArrayList object.

Output

As you can see from the output, the elements added to the TreeSet are automatically sorted in the natural ordering of the elements, which is ascending order for the Integer objects.

Java TreeSet Methods

How to add elements to TreeSet using the add and addAll methods?

The add method of the TreeSet class in Java adds the specified element to the TreeSet only if it is not present and returns true. If the specified element already exists in the TreeSet, the add method does not add the element and returns false.

Output

How to add elements from other Collection to the TreeSet?

The addAll method adds the elements from the specified Collection to this TreeSet object. It returns true if the TreeSet was changed, false otherwise.

The below given example shows how to add all elements of an ArrayList to the TreeSet.

Output

As you can see from the output, only elements that are not already present in the TreeSet are added to it.

How to get elements from the TreeSet?

1. How to get the first element from the TreeSet using the first method?

The first method of the TreeSet class in Java returns the first or the lowest element in the TreeSet.

Output

2. How to get the last element from the TreeSet using the last method?

Just like the first method, the last method of the TreeSet class returns the last element or the largest element of the TreeSet.

Output

3. How to get an element which is higher than the specified element from the TreeSet?

How to get a higher element using the higher method?

The higher method of the TreeSet class returns the smallest element from the TreeSet which is greater than the specified element. If there is no such element in the TreeSet, it returns null.

Output

How to get a higher element using the ceiling method?

The ceiling method returns the smallest element from the TreeSet which is greater than or equal to the specified element. It returns null if no such element exists in the TreeSet.

Output

Difference between higher and ceiling methods: The higher method returns the smallest element that is strictly greater than the specified element. While the ceiling method returns the smallest element which is greater than or equal to the specified element.

4. How to get an element which is lower than the specified element from the TreeSet?

How to get a lower element using the lower method?

The lower method of the TreeSet class returns the greatest element from the TreeSet which is less than the specified element. If there is no such element in the TreeSet, it returns null.

Output

How to get a lower element using the floor method?

The floor method returns the greatest element from the TreeSet which is less than or equal to the specified element. It returns null if no such element exists in the TreeSet.

Output

Difference between lower and floor methods: The lower method returns the greatest element that is strictly less than the specified element. While the floor method returns the greatest element which is less than or equal to the specified element.

How to get the size of the TreeSet using the size method?

The size method of the TreeSet class returns the number of elements that are stored in the TreeSet object. It returns 0 if the TreeSet is empty.

Output

How to check if the TreeSet is empty using the isEmpty method?

The isEmpty method of the TreeSet class returns true if there are no elements in the TreeSet object. It returns false if there is at least one element in it.

Output

Similarly, you can also compare the TreeSet size with 0 to check if the TreeSet is empty. However, using the isEmpty method is recommended way as it clearly states the purpose of the code and is more readable.

How to check if the TreeSet contains the specified element using the contains method?

The contains method of the TreeSet class returns true if the TreeSet contains the specified element. It returns false otherwise.

Output

The contains method throws ClassCastException if the specified element cannot be compared with the elements contained in the TreeSet. It also throws NullPointerException if the specified element is null.

How to Iterate Java TreeSet?

You can iterate TreeSet elements using the iterator with while loop or using the enhanced for loop.

1. Iterate over TreeSet elements using the Iterator

The iterator method of the TreeSet class returns an iterator over the TreeSet elements. To iterate the elements, use hasNext and next methods of the iterator object.

Output

2. Iterate over TreeSet using the enhanced for loop

You can also use the enhanced for loop to iterate through the TreeSet elements.

Output

How to iterate TreeSet in reverse order?

The descendingIterator method returns an iterator over the elements of the TreeSet in descending order.

Output

How to remove elements from the TreeSet?

1. How to remove an element from the TreeSet using the remove method?

The remove method removes the specified element from the TreeSet. The remove method returns true if the set contained the specified element and it was removed. If set does not contain the specified element, it returns false.

Output

2. How to remove all elements from the TreeSet using the clear method?

The clear method of the TreeSet class removes all the elements from the TreeSet or empty the TreeSet object. The TreeSet will be empty after the method call.

Output

3. How to remove the first element from the TreeSet using the pollFirst method?

The pollFirst method of the TreeSet class returns and removes the first element of the TreeSet. It returns null if the TreeSet is empty.

Output

4. How to remove the last element from the TreeSet using the pollLast method?

Just like the pollFirst method, the pollLast method returns and removes the last element from the TreeSet. It returns null if the set is empty.

Output

5. How to remove an element from the TreeSet using the Iterator?

The remove method of the Iterator removes the current element from the underlying TreeSet object.

Output

How to get the subset from the TreeSet?

1. How to get the subset from TreeSet using the subset method?

The subSet method of the TreeSet class returns a portion of the TreeSet whose elements range from the startElement to endElement.

The startElement is inclusive (i.e. included in the subset), while the endElement is exclusive (not included in the subset).

Subset Example:

Output

If you want to control the inclusiveness of the start and end elements, use an overloaded subSet method.

If the startElementInclusive parameter is true, the startElement will be included in the subset. Similarly, if the endElementInclusive parameter is true, the endElement will be included in the subset.

The subset returned from these methods are backed by the original TreeSet. If you make any changes to the subset, it will be reflected back to the TreeSet, and vice versa.

Output

2. How to get a subset containing elements higher than the specified element from the TreeSet?

The tailSet method of the TreeSet class returns a subset whose elements are greater than or equal to the specified element.

Just like the subSet method, The subset returned from this method is backed by the original TreeSet, so any changes you make to the subset will also be reflected back to the original TreeSet.

Output

As you can see from the output, the start element is included in the subset. If you want to exclude it, use an overloaded tailSet method with the boolean parameter.

3. How to get a subset containing elements lower than the specified element from the TreeSet?

The headSet method of the TreeSet class returns a portion or the subset of the TreeSet whose elements are lower than the specified element.

The headset returned by this method is backed by the original TreeSet object. Any changes you make to the subset, it will be reflected back to the TreeSet object, and vice versa.

Output

As you can see from the output, the end element is not included by default. If you want to include it, use an overloaded headSet method with the boolean parameter.

How to reverse the TreeSet using the descendingSet method?

The descendingSet method of the TreeSet class returns a view of the TreeSet elements in the reverse order.

Output

How to convert TreeSet to an array using the toArray method?

The toArray method of the TreeSet class returns an array containing all the elements of the TreeSet object.

If the specified array is big enough to contain all the elements of the TreeSet, the toArray method returns the same array with the TreeSet elements. If not, a new array is created and returned with the TreeSet elements. If the specified array is larger than the size of the TreeSet, the array element that immediately comes after the TreeSet elements is set to null.

Output

You can pass an array of any length to the toArray method. However, it is recommended to pass an array having the same size as the TreeSet object to avoid the performance penalty of allocation of a new array.

How to use the retainAll, removeAll, containsAll, and addAll methods of the TreeSet in Java?

How to remove all the common elements of two TreeSet objects using the removeAll method?

The removeAll method removes all the elements from this TreeSet object that are also present in the specified Collection object.

The removeAll method returns true if this TreeSet object is changed after the method call.

Output

As you can see from the output, all the common elements between two set objects are removed from the TreeSet object. The removeAll method is not restricted only to the TreeSet type, as it accepts any Collection type like ArrayList as well.

How to get an intersection of two TreeSet objects using the retainAll method?

The retainAll method removes all the elements from this TreeSet object that are not present in the specified Collection object, thus keeping only the common elements or an intersection of the two TreeSet objects.

The retainAll method returns true if this TreeSet object is changed after the method call.

Output

As you can see from the output, only the common elements between two set objects are kept in the TreeSet and that leaves the intersection of two TreeSet objects. The retainAll method is not restricted only to the TreeSet, as it accepts any Collection type like ArrayList as well.

How to get a union of two TreeSet objects using the addAll method?

The addAll method of the TreeSet class adds all the elements of the specified TreeSet object to this object. As the TreeSet contains the unique elements, only elements that are missing from this TreeSet objects are added.

Output

As you can see from the output, the TreeSet now contains all the elements present in both the objects. The addAll method accepts the Collection type as a parameter, so you can get a union of TreeSet and ArrayList objects as well.

How to check if a TreeSet object contains all the elements of another TreeSet object?

The containsAll method of the TreeSet object returns true of this TreeSet object contains all the elements of the specified another TreeSet object. It returns false otherwise.

Output

As the containsAll method accepts the Collection type, you can compare elements of the TreeSet with any Collection type like ArrayList.

How to clone a TreeSet object?

The clone method of the TreeSet returns a shallow copy of this TreeSet object. The returned object is not deeply cloned, i.e. only element references are cloned, not the actual objects.

Output

As you can see from the output, when we changed an element in the original TreeSet object, the change is reflected in the cloned TreeSet object as well. That is because both of the TreeSet objects refer to the same elements. However, adding or removing the elements from either the TreeSet objects does not affect the other TreeSet.

Below given are some of the TreeSet examples which show how to use TreeSet in Java.

Java TreeSet Examples

References:
Java TreeSet class Javadoc

Please let me know if you liked the Java TreeSet tutorial with examples in the comments section below.

About the author

Leave a Reply

Your email address will not be published.