When to Use TreeSet
Fast recall
Quick revision
Core answer
TreeSet when the set must stay sorted or needs range and navigation operations such as subSet, floor, ceiling, lower, or higher. Its main operations are O(log n). Use HashSet for expected O(1) membership when order is unnecessary. If sorting is needed only once, a hash set followed by a one-time sort may be simpler, but the best choice depends on update and query patterns.Ability to choose the right data structure based on requirements, understanding performance trade-offs
Using TreeSet when sorting isn't needed, paying O(log n) cost unnecessarily
Give concrete scenarios: finding nearest price, getting words in alphabetical range, maintaining a sorted leaderboard with efficient lookups
Interview-ready guide
Interview answer
I choose TreeSet when sorted order is part of the data structure's job—for example, repeated range queries or finding the nearest value with floor and ceiling. Its add, remove, and contains operations are logarithmic. If I need only uniqueness and membership, HashSet is usually simpler and has expected constant-time operations.
If data is collected once and sorted once at the end, keeping it in a hash set and sorting the final result may be better than paying for ordering on every update. I also make sure the TreeSet ordering is stable and preferably consistent with equals, because comparison result zero defines duplicates in the tree.
When to Use TreeSet
Direct Answer
Use TreeSet when the set must stay sorted or needs range and navigation operations such as subSet, floor, ceiling, lower, or higher. Its main operations are O(log n). Use HashSet for expected O(1) membership when order is unnecessary. If sorting is needed only once, a hash set followed by a one-time sort may be simpler, but the best choice depends on update and query patterns.
Code Example
import java.util.TreeSet;
// Stock prices kept sorted automatically
TreeSet<Integer> prices = new TreeSet<>();
prices.add(120); prices.add(75); prices.add(200); prices.add(95);
System.out.println(prices); // [75, 95, 120, 200] — always sorted
System.out.println(prices.first()); // 75 (cheapest)
System.out.println(prices.last()); // 200 (most expensive)
// Nearest-element lookups (impossible in HashSet)
System.out.println(prices.floor(100)); // 95 -> largest value <= 100
System.out.println(prices.ceiling(100)); // 120 -> smallest value >= 100
// Range query: all prices in [90, 150)
System.out.println(prices.subSet(90, 150)); // [95, 120]
These ordered, range, and nearest-neighbour operations are exactly what justify TreeSet's O(log n) cost over HashSet's O(1).
Common Mistakes & Pitfalls
- Using TreeSet when you only sort once: Freshers see the word sorted and reach for
TreeSet, even when they only sort at the end before displaying — useHashSetduring processing and callstream().sorted()once, avoiding O(log n) on every add. - Ignoring the constant factor: O(log n) sounds fine, but for small-to-medium datasets
HashSet's O(1) with better cache locality is often faster in practice — don't optimize prematurely. - Forgetting the Comparable requirement:
TreeSetneeds elements that implementComparable, or you must supply aComparator— add a custom object without either and you get aClassCastExceptionat runtime.
Check your understanding
Answer these without looking back at the article.
- What is TreeSet.floor(e)?
- How do you sort a Set?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.