Collection Framework - TreeSet

A TreeSet is implemented as a Red-Black Tree, a self-balancing binary search tree, so most of its operations have logarithmic complexity O(log ⁡n).

diagram

Constructor Summary

ConstructorDescription
TreeSet()Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Collection<? extends E> c)Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
TreeSet(Comparator<? super E> comparator)Constructs a new, empty tree set, sorted according to the specified comparator.
TreeSet(SortedSet<E> s)Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.

Method Summary:

MethodComplexity
add(E e)O(logn)
addAll(Collection<? extends E> c)O(m⋅log(n+m))
remove(Object o)O(logn)
pollFirst()O(logn)
pollLast()O(logn)
contains(Object o)O(logn)
first()O(1)
last()O(1)
higher(E e)O(logn) ; Returns the least element in this set strictly greater than the given element, or null if there is no such element.
lower(E e)O(logn) ; Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
size()O(1)

Iterating over TreeSet:

TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Cherry");

// Enhanced for loop
for (String element : treeSet) {
    System.out.println(element);
}

// Using Iterator
Iterator<String> iterator = treeSet.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    System.out.println(element);
}

// Using Lambda expression
treeSet.forEach(element -> System.out.println(element));

// Using stream
treeSet.stream().forEach(System.out::println);