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: • TreeSet maintains elements in sorted order automatically. • HashSet does not guarantee any ordering of elements. • TreeSet is useful when sorted data is required during retrieval. • TreeSet supports operations such as first(), last(), higher(), and lower(). • HashSet generally provides faster performance for basic operations.
When TreeSet Is More Appropriate:
Use TreeSet when:
• Data must remain sorted. • Range-based operations are required. • The smallest or largest element needs to be retrieved frequently. • Ordered reports or rankings must be generated.
Example: Consider a customer management system where customer names must always be displayed alphabetically.
Using TreeSet:
Customer Names:
John
Alex
David
MarkStored Output:
Alex
David
John
MarkThe sorting happens automatically whenever a new name is added.
Code Example:
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:
• Displaying customer names alphabetically • Leaderboards and rankings • Sorted employee records • Generating reports in ascending or descending order • Maintaining a sorted list of product prices
Comparison:
TreeSet: • Maintains sorted order • No duplicate elements • Supports navigation methods • Time Complexity: O(log n)
HashSet: • No guaranteed order • No duplicate elements • Faster lookup and insertion • Average Time Complexity: O(1)
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."