Skip to content
CampusEduX

Collections Framework · Lesson 80 of 150

TreeSet

TreeSet is an implementation of the Set interface that automatically stores its elements in sorted order, based on their natural ordering (like ascending numbers or alphabetical order) or a custom sorting rule you provide.

1 min read

01What is TreeSet?

TreeSet is an implementation of the Set interface that automatically stores its elements in sorted order, based on their natural ordering (like ascending numbers or alphabetical order) or a custom sorting rule you provide.

02Why is it used?

It's useful whenever you need a collection of unique elements that must also stay sorted at all times, without you needing to manually sort them yourself after every addition.

03Real-Life Example

Think of a set of unique exam roll numbers that are always kept arranged in ascending order automatically, no matter in what order students originally submitted their forms. TreeSet maintains this kind of automatic sorted arrangement.

04Syntax

java
TreeSet<DataType> setName = new TreeSet<>();

05Example Program

java
import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(50); numbers.add(10); numbers.add(30); System.out.println(numbers); } }

Output:

[10, 30, 50]

06Key Points to Remember

  • TreeSet keeps elements sorted automatically at all times.
  • It does not allow null elements, since sorting a null value doesn't make sense.
  • TreeSet is generally slower than HashSet due to the extra work of maintaining sorted order.