Java TreeSet Class API or Methods Guide

In this guide, we will learn the usage of TreeSet class APIs/Methods with examples.

TreeSet is one of the most important implementations of the SortedSet interface in Java that internally uses a Tree for storage.

Overview of TreeSet Class

Following are few key points to note about TreeSet in Java -
  • TreeSet cannot contain duplicate elements.
  • The elements in a TreeSet are sorted as per their natural ordering, or based on a custom Comparator that is supplied at the time of creation of the TreeSet.
  • TreeSet cannot contain a null value.
  • TreeSet internally uses a TreeMap to store elements.
  • The TreeSet class internally uses a TreeMap to store elements.
  • This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
  • TreeSet implementation is not synchronized - If multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. Example:
   SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
  • The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

Create TreeSet Example

// Creating a TreeSet
TreeSet<String> fruits = new TreeSet<>();

// Adding new elements to a TreeSet
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Pineapple");
fruits.add("Orange");

System.out.println("Fruits Set : " + fruits);

// Duplicate elements are ignored
fruits.add("Apple");
System.out.println("After adding duplicate element \"Apple\" : " + fruits);

// This will be allowed because it's in lowercase.
fruits.add("banana");
System.out.println("After adding \"banana\" : " + fruits);
Output:
Fruits Set : [Apple, Banana, Orange, Pineapple]
After adding duplicate element "Apple" : [Apple, Banana, Orange, Pineapple]
After adding "banana" : [Apple, Banana, Orange, Pineapple, banana]
Note that in this example, duplicate elements are ignored.

TreeSet with a custom comparator (Case Insensitive Order)

Let's create a TreeSet with a custom comparator that sorts the elements by ignoring the case.
// Creating a TreeSet with a custom Comparator (Case Insensitive Order)
SortedSet<String> weekDays = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
// Adding new elements to a TreeSet
weekDays.add("Monday");
weekDays.add("Tuesday");
weekDays.add("Wednesday");
weekDays.add("Thursday ");
weekDays.add("Friday ");
weekDays.add("Saturday  ");
weekDays.add("Sunday");

System.out.println("weekDays Set : " + weekDays);

// Now, lowercase elements will also be considered as duplicates
weekDays.add("sunday");
System.out.println("After adding \"sunday\" : " + weekDays);
Output:
weekDays Set : [Friday , Monday, Saturday  , Sunday, Thursday , Tuesday, Wednesday]
After adding "sunday" : [Friday , Monday, Saturday  , Sunday, Thursday , Tuesday, Wednesday]
Note that the 'sunday' element is case Insensitive which is ignored.

TreeSet with a custom Comparator Example(Descending order)

// Creating a TreeSet with a custom Comparator (Descending  Order)
SortedSet<String> weekDays = new TreeSet<>(Comparator.reverseOrder());
// Adding new elements to a TreeSet
weekDays.add("Monday");
weekDays.add("Tuesday");
weekDays.add("Wednesday");
weekDays.add("Thursday ");
weekDays.add("Friday ");
weekDays.add("Saturday  ");
weekDays.add("Sunday");

System.out.println("weekDays Set : " + weekDays);
Output:
weekDays Set : [Wednesday, Tuesday, Thursday , Sunday, Saturday  , Monday, Friday ]

Accessing the elements of a TreeSet

Example 1: Find the size of a TreeSet.
TreeSet<String> students = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

students.add("Ramesh");
students.add("Prakash");
students.add("Amir");
// Finding the size of a TreeSet
System.out.println("Number of elements in the TreeSet : " + students.size());
Example 2: Check if an element exists in a TreeSet.
TreeSet<String> students = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

students.add("Ramesh");
students.add("Prakash");
students.add("Amir");

// Check if an element exists in the TreeSet
String name = "Julia";
if(students.contains(name)) {
    System.out.println("TreeSet contains the element : " + name);
} else {
    System.out.println("TreeSet does not contain the element : " + name);
}
Example 3: Find the first element in the TreeSet.
TreeSet<String> students = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

students.add("Ramesh");
students.add("Prakash");
students.add("Amir");

// Navigating through the TreeSet
System.out.println("First element : " + students.first());
Example 4: Find the last element in the TreeSet.
TreeSet<String> students = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

students.add("Ramesh");
students.add("Prakash");
students.add("Amir");
System.out.println("Last element : " + students.last());
Example 5: Find the element just higher than the given element in the TreeSet.
TreeSet<String> students = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

students.add("Ramesh");
students.add("Prakash");
students.add("Amir");
String name = "amir";
System.out.println("Element just greater than "  + name + " : " + students.higher(name));
Example 6: Find the element just lower than the given element in the TreeSet.
TreeSet<String> students = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

students.add("Ramesh");
students.add("Prakash");
students.add("Amir");
String name = "amir";
System.out.println("Element just lower than "  + name + " : " + students.lower(name));

Removing elements from a TreeSet

Example 1: Remove an element from a TreeSet.
TreeSet<Integer> numbers = new TreeSet<>();

numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);

// Remove an element from the TreeSet
boolean isRemoved = numbers.remove(49);
Example 2: Remove all elements that satisfy a given predicate.
TreeSet<Integer> numbers = new TreeSet<>();

numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);
// Remove all elements divisible by 3
numbers.removeIf(number -> number % 3 == 0);
Example 3: Remove the first element of the TreeSet.
TreeSet<Integer> numbers = new TreeSet<>();

numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);
// Retrieve and remove the first element from the TreeSet
Integer num = numbers.pollFirst();
System.out.println("Removed first element " + num + " from the TreeSet : " + numbers);
Example 4: Remove the last element of the TreeSet.
TreeSet<Integer> numbers = new TreeSet<>();

numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);
// Retrieve and remove the last element from the TreeSet
num = numbers.pollLast();
System.out.println("Removed last element " + num + " from the TreeSet : " + numbers);

Related Collections Framework API Guides

References

https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/TreeSet.html

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course