TreeSet is a better choice than HashSet when elements need to be stored in a sorted order. While HashSet focuses on fast insertion and lookup without guaranteeing any order, TreeSet automatically arranges elements according to their natural ordering or a custom Comparator.
Consider a customer management system where customer names must always be displayed alphabetically.
John
Alex
David
MarkAlex
David
John
MarkThe sorting happens automatically whenever a new name is added.
import java.util.Set;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
Set<String> customers =
new TreeSet<>();
customers.add("John");
customers.add("Alex");
customers.add("David");
customers.add("Mark");
System.out.println(customers);
}
}[Alex, David, John, Mark]
What Happens with HashSet?
Set<String> customers =
new HashSet<>();
customers.add("John");
customers.add("Alex");
customers.add("David");
customers.add("Mark");[Mark, John, Alex, David]
The order is unpredictable and may vary between executions.
A concise interview answer is
TreeSet is more appropriate than HashSet when elements must be maintained in sorted order. For example, if customer names need to be displayed alphabetically or product prices must be stored in ascending order, TreeSet automatically keeps the data sorted, whereas HashSet does not guarantee any ordering.
Last updated: 16 July 2026
Previous question: Why must you override hashCode() when you override equals(), and what happens if you don't?
Next question: What is the internal implementation of ArrayList and LinkedList?