Can you give an example where a TreeSet is more appropriate than HashSet?

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.

Key Points

When TreeSet Is More Appropriate

Use TreeSet when

Example

Consider a customer management system where customer names must always be displayed alphabetically.

Using TreeSet

Customer Names

John
Alex
David
Mark

Stored Output

Alex
David
John
Mark

The 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);
    }
}

Output

[Alex, David, John, Mark]

What Happens with HashSet?

Code

Set<String> customers =
        new HashSet<>();

customers.add("John");
customers.add("Alex");
customers.add("David");
customers.add("Mark");

Possible Output

[Mark, John, Alex, David]

The order is unpredictable and may vary between executions.

Real-World Use Cases for TreeSet

Comparison

TreeSet

HashSet

Interview Tip

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?

More Core Java - Level II interview questions

All Core Java - Level II questions