Quick revision
The short answer
Because a TreeSet keeps its elements sorted, it offers NavigableSet operations a HashSet cannot: first and last, and floor, ceiling, lower and higher to find the nearest neighbours of a value in O(log n); headSet, tailSet and subSet, which return live range views backed by the set; pollFirst and pollLast, which remove and return the smallest or largest element; and descendingSet for reverse order. A practical example is finding the next available appointment slot with ceiling(requestedTime). Range views reject inserts outside their range with IllegalArgumentException.
What to remember
In this answer, we saw that TreeSet's sorted red-black tree enables NavigableSet operations that a HashSet cannot offer: first, last, floor, ceiling, lower and higher find neighbours in O(log n); headSet, tailSet and subSet return live views backed by the set; pollFirst and pollLast remove the extremes; and descendingSet gives reverse order. We used ceiling(requestedTime) to find the next free appointment slot, and saw that range views throw IllegalArgumentException for inserts outside their range.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Because a TreeSet keeps its elements sorted, it offers NavigableSet operations a HashSet cannot: first and last, and floor, ceiling, lower and higher to find the nearest neighbours of a value in O(log n); headSet, tailSet and subSet, which return live range views backed by the set; pollFirst and pollLast, which remove and return the smallest or largest element; and descendingSet for reverse order. A practical example is finding the next available appointment slot with ceiling(requestedTime). Range views reject inserts outside their range with IllegalArgumentException.
Why this question is asked
Sets are usually introduced as collections without duplicates, and HashSet is the default choice. But many real problems ask questions about order: what is the next free slot, which prices fall in this band, what is the smallest pending deadline. A HashSet cannot answer any of these without scanning every element. Interviewers ask this question to see whether we know that TreeSet is more than a sorted HashSet and can name the operations that make it useful. In this answer, we will recap how TreeSet stores its elements, go through the neighbour operations, the range views and the polling methods, use ceiling to book an appointment slot, and finish with the trap in range views.
1A Quick Recap of TreeSet and NavigableSet
A TreeSet stores its elements in a red-black tree, a binary search tree that rebalances on every change so its height stays around log2(n). Elements are ordered by their natural order, through compareTo, or by a Comparator passed to the constructor. Because the tree is ordered, TreeSet can go left or right at each node to find not only an exact element, but also the elements nearest to any value.
These order-based operations are declared in NavigableSet, which TreeSet implements and which extends SortedSet. A HashSet stores elements by hash code, which has nothing to do with order, so none of these operations is possible there without sorting first.
2Finding Neighbours: first, last, floor, ceiling, lower, higher
The neighbour methods differ in whether they include the value itself and in which direction they look. floor(x) returns the greatest element less than or equal to x, ceiling(x) the smallest greater than or equal to x, lower(x) the greatest strictly less than x, and higher(x) the smallest strictly greater than x. Each returns null if no such element exists, and each takes O(log n).
| Call | Rule | Result |
|---|---|---|
floor(25) | greatest <= 25 | 20 |
ceiling(25) | smallest >= 25 | 30 |
lower(30) | greatest < 30 | 20 |
higher(30) | smallest > 30 | 40 |
ceiling(45) | smallest >= 45 | null |
Notice the difference between floor(30) and lower(30): the first includes the value, the second does not. That single distinction is a common source of off-by-one bugs, so it is worth saying the definitions precisely in an interview. first() and last(), unlike the others, throw NoSuchElementException on an empty set rather than returning null.
3Range Views: headSet, tailSet, subSet
The range methods return a view of part of the set, not a copy. headSet(x) contains elements below x, tailSet(x) those from x upwards, and subSet(a, b) those from a up to but not including b; overloads with boolean flags let us choose inclusive or exclusive ends. Because they are views, they reflect later changes to the set, and changes through the view, such as remove, change the set.
4Removing the Extremes and Reversing
pollFirst() removes and returns the smallest element, and pollLast() the largest; both return null on an empty set. They make a TreeSet a simple sorted work queue in which duplicates are not allowed, for example processing deadlines from the earliest. descendingSet() returns a reversed view, and descendingIterator() iterates from the largest element down.
5A Practical Use: The Next Available Appointment Slot
A clinic keeps its free slots in a TreeSet<LocalDateTime>. When a patient asks for a time, we offer the requested time if it is free, otherwise the next free slot after it. That is exactly ceiling.
With a HashSet, we would have to scan every free slot and keep the smallest one after the requested time, which is O(n) per request. With TreeSet, it is O(log n), and the code says what it means. In a real system, booking also needs the check and the removal to happen together under a lock or in the database, so two patients cannot get the same slot.
6The Trap in Range Views
A range view remembers its bounds. If we try to add an element outside them through the view, it throws instead of silently adding the element to the backing set.
The reason is that the view promises to contain only elements in its range. Adding 40 through it would either break that promise or have to be silently ignored, and both would be surprising. Adding 40 directly to s is fine, and the view simply does not show it.
7Follow-up questions
What does a TreeSet need from its elements?
A consistent ordering: either the elements implement Comparable, or we pass a Comparator. Without either, the first add of a non-comparable element throws ClassCastException. TreeSet also uses that ordering, not equals, to decide whether two elements are duplicates.
Does TreeSet allow null?
Not with natural ordering, because compareTo on null throws NullPointerException. A Comparator that handles null, such as Comparator.nullsFirst(Comparator.naturalOrder()), allows one null element. In practice, avoiding null in sorted sets is simpler.
Is TreeSet thread-safe?
No. For concurrent use, ConcurrentSkipListSet implements the same NavigableSet methods, with O(log n) expected cost and weakly consistent iterators and views.
8Conclusion
In this answer, we saw that TreeSet's sorted red-black tree enables NavigableSet operations that a HashSet cannot offer: first, last, floor, ceiling, lower and higher find neighbours in O(log n); headSet, tailSet and subSet return live views backed by the set; pollFirst and pollLast remove the extremes; and descendingSet gives reverse order. We used ceiling(requestedTime) to find the next free appointment slot, and saw that range views throw IllegalArgumentException for inserts outside their range.
Open with
Because TreeSet is a sorted red-black tree, it implements NavigableSet, which gives operations a HashSet cannot do without scanning everything. first and last give the smallest and largest elements. floor and ceiling give the nearest element at or below, or at or above, a value; lower and higher are the strict versions.
Then, if they want more
All of these are O(log n) and return null when there is no such element, except first and last, which throw on an empty set. Then there are range views: headSet, tailSet and subSet, with optional inclusive flags.
They are live views backed by the set, so changes in either show in the other. pollFirst and pollLast remove and return the extremes, which makes a TreeSet handy as a sorted queue of unique items, and descendingSet gives a reversed view.
A practical use is booking: keep free appointment slots in a TreeSet of LocalDateTime, and ceiling of the requested time gives the requested slot if it is free, or the next one after it, in log n instead of scanning all slots.
One trap with range views: they remember their bounds, so adding an element outside the range through the view throws IllegalArgumentException, even though adding it to the main set is fine.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Name the NavigableSet operations of TreeSet that you cannot get from a HashSet, and give...": https://scrivio-interview-library.netlify.app/java/sets/334d4c3d98/