0Pricing
Java Academy · Lesson

TreeSet and NavigableSet

Store unique sorted elements and use floor, ceiling, higher, lower for nearest-neighbor queries.

What is TreeSet?

TreeSet is a sorted set backed by a Red-Black tree. It stores unique elements in ascending natural order (or a provided comparator). All operations are O(log n).

import java.util.TreeSet;

TreeSet<String> names = new TreeSet<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
names.add("Alice"); // duplicate ignored

for (String s : names) System.out.print(s + " ");
// Alice Bob Charlie

NavigableSet Methods: floor, ceiling, lower, higher

TreeSet implements NavigableSet, providing navigation methods to find the nearest elements:

TreeSet<Integer> set = new TreeSet<>();
for (int i = 10; i <= 50; i += 10) set.add(i);
// {10, 20, 30, 40, 50}

System.out.println(set.floor(25));   // 20 (greatest ≤ 25)
System.out.println(set.ceiling(25)); // 30 (smallest ≥ 25)
System.out.println(set.lower(30));   // 20 (strictly less)
System.out.println(set.higher(30));  // 40 (strictly greater)

All lessons in this course

  1. TreeMap: Sorted Key-Value Pairs
  2. Submaps and Range Views
  3. TreeSet and NavigableSet
  4. Custom Ordering in Tree Collections
← Back to Java Academy