Sobes.tech
Junior — Middle

What is the main role of the Comparator interface in Java and why is it used?

sobes.tech AI

Answer from AI

The Comparator interface in Java is used to define the order of objects when the natural order (via Comparable) is not suitable or absent. It allows you to specify custom comparison logic for two objects, which is useful when sorting collections or arrays by different criteria.

Example of using Comparator to sort a list of strings by length:

import java.util.*;

List<String> list = Arrays.asList("apple", "banana", "pear");
Collections.sort(list, new Comparator<String>() {
    public int compare(String s1, String s2) {
        return Integer.compare(s1.length(), s2.length());
    }
});
// Now the list is sorted by string length

Since Java 8, lambda expressions can be used to simplify this:

Collections.sort(list, (s1, s2) -> Integer.compare(s1.length(), s2.length()));
What is the main role of the Comparator interface in… - sobes.tech