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.
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
javaTreeSet<DataType> setName = new TreeSet<>();
05Example Program
javaimport 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
TreeSetkeeps elements sorted automatically at all times.- It does not allow
nullelements, since sorting anullvalue doesn't make sense. TreeSetis generally slower thanHashSetdue to the extra work of maintaining sorted order.