TreeSet and NavigableSet
Store unique sorted elements and use floor, ceiling, higher, lower for nearest-neighbor queries.
TreeSet and NavigableSet is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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 CharlieNavigableSet 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)first, last, pollFirst, pollLast
Access or remove the boundary elements:
TreeSet<String> ts = new TreeSet<>(Set.of("cherry","apple","banana","date"));
System.out.println(ts.first()); // apple
System.out.println(ts.last()); // date
System.out.println(ts.pollFirst()); // apple (removed)
System.out.println(ts.pollLast()); // date (removed)
System.out.println(ts); // [banana, cherry]headSet, tailSet, subSet
Extract sorted subset views:
TreeSet<Integer> set = new TreeSet<>(Set.of(1,2,3,4,5,6,7,8,9,10));
System.out.println(set.headSet(5)); // [1, 2, 3, 4]
System.out.println(set.tailSet(7)); // [7, 8, 9, 10]
System.out.println(set.subSet(3, 7)); // [3, 4, 5, 6]
// Inclusive upper bound:
System.out.println(set.subSet(3, true, 7, true)); // [3,4,5,6,7]Descending Iteration
Use descendingIterator() or descendingSet() for reverse order:
TreeSet<Integer> ts = new TreeSet<>(Set.of(1,3,5,7,9));
// Descending iterator
var it = ts.descendingIterator();
while (it.hasNext()) System.out.print(it.next() + " ");
// 9 7 5 3 1Custom Ordering via Comparator
Pass a Comparator to sort by a non-natural order — for example, longest string first:
TreeSet<String> byLength = new TreeSet<>(
Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder())
);
byLength.add("Hi");
byLength.add("Hello");
byLength.add("Hey");
byLength.add("Java");
for (String s : byLength) System.out.print(s + " ");
// Hi Hey Java HelloUse Case: Sorted Unique Usernames
Store usernames in a TreeSet to automatically deduplicate and maintain alphabetical order:
TreeSet<String> users = new TreeSet<>();
users.add("alice");
users.add("bob");
users.add("alice"); // ignored
users.add("carol");
System.out.println(users.first()); // alice
System.out.println(users); // [alice, bob, carol]Use Case: Range Counting
Count elements in a range using subSet:
TreeSet<Integer> scores = new TreeSet<>();
for (int s : new int[]{45,62,78,55,90,88,34,71}) scores.add(s);
// Scores between 60 and 89 (inclusive)
int count = scores.subSet(60, true, 89, true).size();
System.out.println("Students in B range: " + count); // 3 (62, 78, 88... wait: 62,78,71,88=4)
// Actually: 62,71,78,88 = 4TreeSet vs HashSet vs LinkedHashSet
Choose based on needs:
- HashSet: O(1) operations, unordered
- LinkedHashSet: O(1) operations, insertion-ordered
- TreeSet: O(log n) operations, sorted order, navigation methods
TreeSet requires elements to implement Comparable or a Comparator.
Null Elements
TreeSet does NOT allow null elements when using natural ordering — a NullPointerException is thrown because null cannot be compared. A custom comparator that handles null explicitly would work.
TreeSet<String> ts = new TreeSet<>();
try {
ts.add(null); // throws NullPointerException
} catch (NullPointerException e) {
System.out.println("Cannot add null: " + e);
}Thread Safety
TreeSet is NOT thread-safe. Synchronize externally with Collections.synchronizedSortedSet(), or use ConcurrentSkipListSet which is both sorted and thread-safe.
Quick Check
A TreeSet<Integer> contains {10, 20, 30, 40, 50}. What does set.ceiling(35) return?
Recap: TreeSet and NavigableSet
Key takeaways:
- TreeSet stores unique sorted elements (O(log n))
- Implements NavigableSet: floor, ceiling, lower, higher, first, last
- headSet, tailSet, subSet return backed range views
- Use descendingSet()/descendingIterator() for reverse order
- Not thread-safe — use ConcurrentSkipListSet for concurrency
Frequently asked questions
Is the “TreeSet and NavigableSet” lesson free?
Yes — the full text of “TreeSet and NavigableSet” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “TreeSet and NavigableSet”?
Store unique sorted elements and use floor, ceiling, higher, lower for nearest-neighbor queries. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “TreeSet and NavigableSet” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- TreeMap: Sorted Key-Value Pairs
- Submaps and Range Views
- TreeSet and NavigableSet
- Custom Ordering in Tree Collections