How to use Comparator in Java to sort
To use a Comparator
in Java to sort a list of objects, you can use the Collections.sort
method and pass it a List
and a Comparator
. The Comparator
specifies the ordering of the elements in the list. Here's an example of how to use the Collections.sort
method to sort a List
of strings using a Comparator
:
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = List.of("apple", "banana", "cherry");
Collections.sort(list, new MyComparator());
System.out.println(list); // output: [banana, apple, cherry]
}
static class MyComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
}
In this example, the MyComparator
class implements the Comparator
interface and overrides the compare
method. The compare
method compares the length of the strings and returns a negative value if the first string is shorter, a positive value if the first string is longer, and 0 if the strings are the same length. This causes the list to be sorted by string length, with the shortest strings coming first.
You can also use the Comparator.comparing
method to create a comparator that