TreeSet in Java: Mastering Java Course

Mastering Java Course: Set: TreeSet in Java

CS IITIAN
CodeX
5 min readSep 30, 2023

--

I have published blog on Set in Java, where I have discussed 3 mostly used types of Set in Java

  1. HashSet
  2. LinkedHashSet
  3. TreeSet

In this blog I will be focusing on TreeSet.

When it comes to working with ordered collections of elements in Java, TreeSet is a versatile choice. It's part of the Java Collections Framework and implements the NavigableSet interface, making it efficient for various operations. In this guide, we'll explore key methods of TreeSet along with code examples.

Creating a TreeSet

You can create a TreeSet and add elements to it like this:

import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Create a TreeSet of integers
TreeSet<Integer> treeSet = new TreeSet<>();
// Add elements
treeSet.add(5);
treeSet.add(2);
treeSet.add(8);
}
}

Iterating through a TreeSet

You can use an iterator to traverse the elements in ascending order:

for (Integer element : treeSet) {
System.out.println(element);
}

Checking if an Element Exists

You can check if a specific element exists in the TreeSet using the contains method:

boolean exists = treeSet.contains(5); // Returns true
boolean notExists = treeSet.contains(10); // Returns false

Removing Elements

To remove an element from the TreeSet, use the remove method:

treeSet.remove(2); // Removes 2 from the set

Finding the First and Last Element

You can find the first (lowest) and last (highest) elements in the TreeSet using first() and last():

Integer firstElement = treeSet.first(); // Returns the lowest element 2
Integer lastElement = treeSet.last(); // Returns the highest element 8

Using ceiling() and floor()

The ceiling method finds the least element greater than or equal to a given value, while floor finds the greatest element less than or equal to a given value:

throws NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

Integer greaterOrEqual = treeSet.ceiling(4); // Returns 5
Integer lessOrEqual = treeSet.floor(3); // Returns 2

Using higher() and lower()

higher() returns the least element strictly greater than the given value, and lower() returns the greatest element strictly less than the given value:

Integer strictlyGreater = treeSet.higher(3); // Returns 5
Integer strictlyLess = treeSet.lower(5); // Returns 2

Creating Subsets

You can create subsets of a TreeSet using the subSet method:

// Create a subset of elements between 2 (inclusive) and 8 (exclusive)
TreeSet<Integer> subset = new TreeSet<>(treeSet.subSet(2, 8));

Tail Set and Head Set

tailSet and headSet methods return views of the portion of the set:

// Get a tree set containing elements greater than or equal to 5
TreeSet<Integer> tail = new TreeSet<>(treeSet.tailSet(5));
// Get a tree set containing elements less than or equal to 5
TreeSet<Integer> head = new TreeSet<>(treeSet.headSet(5));

Polling Elements

You can retrieve and remove the first (lowest) and last (highest) elements using pollFirst() and pollLast():

Integer firstElement = treeSet.pollFirst(); // Removes and returns the lowest element
Integer lastElement = treeSet.pollLast(); // Removes and returns the highest element

Clearing the TreeSet

To remove all elements from the TreeSet, use the clear method:

treeSet.clear(); // Removes all elements

Final Code

import java.util.TreeSet;

public class TreeSetBlog {
public static void main(String[] args) {

TreeSet<Integer> set = new TreeSet<>();

// add(x)
set.add(5);
set.add(2);
set.add(1);
set.add(8);

System.out.println("set is " + set);

// contains(x)
if(set.contains(5)) {
System.out.println("contains(x) => set contains 5");
} else {
System.out.println("contains(x) => set doesn't contain 5");
}

// remove(x)
set.remove(1);
System.out.println("remove(1) => after removing 1 set is " + set);

// first() and last()
int lowest = set.first();
System.out.println("first() => lowest element in " + set + " is " + lowest);

int highest = set.last();
System.out.println("last() => highest element in " + set + " is " + highest);

// ceiling(x) and floor(x)
Integer ceilingOf6 = set.ceiling(6);
if(ceilingOf6 != null) {
System.out.println("ceiling(6) => " + ceilingOf6 + " is greater than or equal to 6 in set " + set);
}

Integer floorOf6 = set.floor(6);
if(floorOf6 != null) {
System.out.println("floor(6) => " + floorOf6 + " is less than or equal to 6 in set " + set);
}

Integer floorOf5 = set.floor(5);
if(floorOf5 != null) {
System.out.println("floor(5) => " + floorOf5 + " is less than or equal to 5 in set " + set);
}

// higher(x) and lower(x)
Integer strictlyGreaterThan6 = set.higher(6);
if(strictlyGreaterThan6 != null) {
System.out.println("higher(6) => " + strictlyGreaterThan6 + " is greater than 6 in set " + set);
}

Integer strictlyGreaterThan5 = set.higher(5);
if(strictlyGreaterThan5 != null) {
System.out.println("higher(5) => " + strictlyGreaterThan5 + " is greater than 6 in set " + set);
}

Integer strictlyLessThan6 = set.lower(6);
if(strictlyLessThan6 != null) {
System.out.println("lower(6) => " + strictlyLessThan6 + " is less than 6 in set " + set);
}

// subset(l,h) - l ( inclusive) and r ( exclusive )
TreeSet<Integer> subSet = new TreeSet<>(set.subSet(2, 8));
System.out.println("subset(2,8) => " + subSet + " contains element between 2(inclusive)-8(exclusive) from set " + set);

// tailSet(l) and headSet(h)
TreeSet<Integer> tailSet = new TreeSet<>(set.tailSet(5));
System.out.println("tailSet(5) => " + tailSet + " contains element greater than or equal to 5 from set " + set);

TreeSet<Integer> headSet = new TreeSet<>(set.headSet(5));
System.out.println("headSet(5) => " + headSet + " contains element less than or equal to 5 from set " + set);

// pollFirst() and pollLast()
Integer firstElement = set.pollFirst(); // Removes and returns the lowest element
System.out.println("pollFirst() => " + firstElement + " is removed, now set is " + set);
Integer lastElement = set.pollLast(); // Removes and returns the highest element
System.out.println("pollLast() => " + lastElement + " is removed, now set is " + set);

// clear()
set.clear();
System.out.println("clear() => after removing all elements, now set is " + set);
}
}

Output

set is [1, 2, 5, 8]
contains(x) => set contains 5
remove(1) => after removing 1 set is [2, 5, 8]
first() => lowest element in [2, 5, 8] is 2
last() => highest element in [2, 5, 8] is 8
ceiling(6) => 8 is greater than or equal to 6 in set [2, 5, 8]
floor(6) => 5 is less than or equal to 6 in set [2, 5, 8]
floor(5) => 5 is less than or equal to 5 in set [2, 5, 8]
higher(6) => 8 is greater than 6 in set [2, 5, 8]
higher(5) => 8 is greater than 6 in set [2, 5, 8]
lower(6) => 5 is less than 6 in set [2, 5, 8]
subset(2,8) => [2, 5] contains element between 2(inclusive)-8(exclusive) from set [2, 5, 8]
tailSet(5) => [5, 8] contains element greater than or equal to 5 from set [2, 5, 8]
headSet(5) => [2] contains element less than or equal to 5 from set [2, 5, 8]
pollFirst() => 2 is removed, now set is [5, 8]
pollLast() => 8 is removed, now set is [5]
clear() => after removing all elements, now set is []

Process finished with exit code 0

Conclusion

Understanding the methods of TreeSet is essential for effectively working with ordered sets in Java. This guide has covered key methods and provided code examples to get you started. Explore further and leverage TreeSet to simplify your Java programming tasks.

References

--

--

CS IITIAN
CodeX

Funny Grand Son | Good Son | Supportive Brother | Software Engineer | Non Reactive | Nothing to Loose