Junior — Middle
What is the purpose of a comparator and how is it used in programming?
sobes.tech AI
Answer from AI
A comparator is an object or function designed to compare two elements to determine their order. In programming, a comparator is used for sorting, searching, or ordering collections of data.
In Java, a comparator is implemented through the Comparator<T> interface, which requires the implementation of the compare(T o1, T o2) method. This method returns:
- a negative number if
o1is less thano2; - zero if they are equal;
- a positive number if
o1is greater thano2.
An example of using a comparator to sort a list of strings by length:
List<String> list = Arrays.asList("apple", "banana", "kiwi");
list.sort(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
});
// Now the list is sorted by string length
Comparators allow flexible criteria for sorting without modifying the objects themselves.