To store elements in a sorted manner, Java provides TreeSet and TreeMap. These collections automatically maintain elements in sorted order, either based on their natural ordering or a custom Comparator supplied by the developer.
Key Points: • TreeSet stores unique elements in sorted order. • TreeMap stores key-value pairs with keys maintained in sorted order. • Sorting can be based on natural ordering or a custom Comparator. • Elements are automatically reordered whenever new data is added. • Both TreeSet and TreeMap are implemented using a Red-Black Tree.
Using TreeSet
TreeSet automatically sorts elements and does not allow duplicates.
Example:
TreeSet<Integer> numbers =
new TreeSet<>();
numbers.add(30);
numbers.add(10);
numbers.add(20);Output:
[10, 20, 30]
Characteristics:
• Sorted order maintained automatically • No duplicate values • O(log n) insertion and search operations
Using TreeMap
TreeMap stores data as key-value pairs and keeps keys sorted.
Example:
TreeMap<Integer, String> employees =
new TreeMap<>();
employees.put(102, "John");
employees.put(101, "David");Output:
{101=David, 102=John}
Characteristics:
• Keys are automatically sorted • Values can be duplicated • Efficient searching and retrieval
Example: Suppose we want to store employee IDs in ascending order.
Code Example:
import java.util.Set;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
Set<Integer> employeeIds =
new TreeSet<>();
employeeIds.add(105);
employeeIds.add(101);
employeeIds.add(103);
employeeIds.add(102);
System.out.println(employeeIds);
}
}Output:
[101, 102, 103, 105]
Custom Sorting Using Comparator
TreeSet can also sort elements according to custom business rules.
Example:
TreeSet<String> names = new TreeSet<>( (a, b) -> b.compareTo(a) );
This sorts elements in descending order.
Comparison of Common Collections:
HashSet: • Unordered • No duplicates • Fastest lookup
LinkedHashSet: • Maintains insertion order • No duplicates
TreeSet: • Maintains sorted order • No duplicates
HashMap: • Unordered keys • Key-value storage
TreeMap: • Sorted keys • Key-value storage
Real-World Use Cases:
• Ranking systems • Leaderboards • Sorted employee records • Product catalogs • Generating reports in sorted order
Interview Tip: A concise interview answer is:
"To store elements in sorted order, use TreeSet for unique elements or TreeMap for key-value pairs. Both collections automatically sort data using natural ordering or a custom Comparator and maintain the sorted order whenever elements are added or removed."