What is TreeSet in Java?

A TreeSet in Java is a part of the Java Collections Framework that implements the Set interface. It is a collection that stores elements in a sorted (natural order or a specified comparator) manner. TreeSet is backed by a Red-Black tree, which is a self-balancing binary search tree, ensuring that the set remains sorted. Because of its nature, TreeSet does not allow duplicate elements, and the elements must be mutually comparable.

Key Features of TreeSet:

  • Sorted order of elements
  • No duplicates allowed
  • Faster operations for sorted data, i.e., O(log n) time complexity for add, remove, and contains operations

Example Code:

import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { TreeSet<String> treeSet = new TreeSet<>(); treeSet.add("Apple"); treeSet.add("Banana"); treeSet.add("Orange"); treeSet.add("Grapes"); System.out.println("TreeSet: " + treeSet); } }

TreeSet Java collections framework sorted set Red-Black tree elements unique comparator