← Back to Chapters

TreeSet in Java

? TreeSet in Java

? Quick Overview

TreeSet is a class in Java that implements the SortedSet interface. It stores unique elements in sorted order and internally uses a Red-Black Tree.

? Key Concepts

  • Does not allow duplicate elements
  • Elements are stored in sorted (ascending) order
  • Allows null only once (and often avoided)
  • Not synchronized by default
  • Slower than HashSet but maintains order

? Interactive Playground

Type a number and click Add. Watch how it sorts automatically and rejects duplicates!

 
Current Set: []

? Syntax / Theory

? View Code Example
// Creating a TreeSet of Integer type
TreeSet<Integer> numbers = new TreeSet<>();

? Code Example(s)

? View Code Example
// Demonstration of TreeSet operations
import java.util.TreeSet;

public class Main {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();

set.add(50);
set.add(10);
set.add(30);
set.add(10);

System.out.println(set);
}
}

?️ Live Output / Explanation

Output

[10, 30, 50]

Elements are automatically sorted and duplicate values are ignored.

✅ Tips & Best Practices

  • Use TreeSet when sorted data is required
  • Avoid null values to prevent exceptions
  • Prefer HashSet if ordering is not needed
  • Use Comparator for custom sorting

? Try It Yourself

  1. Create a TreeSet of Strings
  2. Add names in random order
  3. Print the TreeSet and observe sorting
  4. Apply a custom Comparator