What is TreeSet

TreeSet – It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.

In Core Java, a TreeSet is a class that implements the Set interface and extends the AbstractSet class. It is part of the Java Collections Framework and is part of the java.util package.

A TreeSet is a NavigableSet implementation based on a TreeMap. It uses a Red-Black tree structure to maintain the elements in sorted order. The elements are sorted in their natural order or according to a specified comparator.

Key characteristics of a TreeSet:

  1. Ordered: The elements are stored in ascending order (natural order) or according to a custom comparator.
  2. Unique Elements: A TreeSet does not allow duplicate elements. If you attempt to add an element that is already present, the operation will have no effect.
  3. Null Elements: A TreeSet does not allow null elements. If you try to add a null element, a NullPointerException will be thrown.

Here’s a simple example of using a TreeSet:

java
import java.util.TreeSet;

public class TreeSetExample {
public static void main(String[] args) {
// Creating a TreeSet
TreeSet<String> treeSet = new TreeSet<>();

// Adding elements
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Orange");
treeSet.add("Grapes");

// Displaying the elements
System.out.println("TreeSet elements: " + treeSet);
}
}

This would output:

less
TreeSet elements: [Apple, Banana, Grapes, Orange]

In this example, the elements are stored in alphabetical order, as strings have a natural ordering.