Comparator Chaining
We can chain the comparator as following:
public class Application {
public static void main(String[] args) {
List<Integer> list = List.of(1,3,4);
Comparator<Integer> firstComparator = (a, b) -> {
System.out.printf("1. %s %s%n", b, a);
return a - b;
};
Comparator<Integer> secondComparator = (a, b) -> {
System.out.printf("2. %s %s%n", b, a);
return a - b;
};
System.out.println(list.stream().sorted(firstComparator.thenComparing(secondComparator)).collect(Collectors.toList()));
}
}
Or
public class Application {
public static void main(String[] args) {
List<Integer> list = List.of(1,3,4);
Comparator<Integer> firstComparator = (a, b) -> {
System.out.printf("1. %s %s%n", b, a);
return a - a;
};
Comparator<Integer> mergedComparator = firstComparator.thenComparing((a, b) -> {
System.out.printf("2. %s %s%n", b, a);
return a - b;
});
System.out.println(list.stream().sorted(mergedComparator).collect(Collectors.toList()));
}
}
[!note]
The second comparator here is only used for fallback, it only executes when the first comparator is equal, then it compares the second comparator.