Junior — Middle
For what task is the Comparator interface used in the TreeMap data structure?
sobes.tech AI
Answer from AI
The Comparator interface in the TreeMap data structure is used to define the sorting order of keys. TreeMap stores elements in sorted order, and Comparator allows you to specify a custom way of comparing keys, different from the natural order (Comparable). This is especially useful when keys do not implement Comparable or when sorting by a non-standard criterion.
Example of using Comparator with TreeMap:
import java.util.*;
public class Example {
public static void main(String[] args) {
// Sorting keys in reverse order
Comparator<String> reverseOrder = (s1, s2) -> s2.compareTo(s1);
TreeMap<String, Integer> map = new TreeMap<>(reverseOrder);
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
System.out.println(map); // {cherry=3, banana=2, apple=1}
}
}