Junior — Middle
In which design pattern is the Comparator class used for comparing objects?
sobes.tech AI
Answer from AI
The Comparator class in Java is used in the Strategy design pattern.
Comparator implements an interface that defines a comparison strategy for objects. This allows changing the comparison method without modifying the classes of the objects themselves.
For example, if you have a list of objects and want to sort them by different criteria, you can create different Comparator implementations and pass them to sorting methods:
List<Person> people = ...;
// Sorting by name
Comparator<Person> byName = (p1, p2) -> p1.getName().compareTo(p2.getName());
// Sorting by age
Comparator<Person> byAge = Comparator.comparingInt(Person::getAge);
Collections.sort(people, byName);
Collections.sort(people, byAge);
Thus, Comparator allows flexible changing of the comparison algorithm, which corresponds to the Strategy pattern.