Functional Interfaces: Comparator

Compares two values for the purpose of ordering.

Overview

Examples

Sort array by reciprocal values using Arrays.sort(T[], Comparator):

Integer[] data = {-1, 3, 2, 10, -5, 6};
Arrays.sort(data, (d1, d2) -> Double.compare(1.0 / d1, 1.0 / d2));
System.out.println(Arrays.toString(data));

Sort List by reciprocal values using List.sort(Comparator):

List<Integer> data = new LinkedList<>(List.of(-1, 3, 2, 10, -5, 6));
data.sort((d1, d2) -> Double.compare(1.0 / d1, 1.0 / d2));
System.out.println(data);

Sort the items processed by a Stream by reciprocal values using Stream.sorted(Comparator):

System.out.println(Stream.of(-1, 3, 2, 10, -5, 6)
    .sorted((d1, d2) -> Double.compare(1.0 / d1, 1.0 / d2))
    .collect(Collectors.toList()));

Output

All of the above produce the same output:

[-1, -5, 10, 6, 3, 2]