You can reduce stream of comparators to one comparator by calling .thenComparing() on the accumulated comparator and the current comparator on iteration:
Optional<Comparator<O>> comparator = Optional.ofNullable(comparators.stream() .reduce(null, (acc, current) -> acc == null ? current : acc.thenComparing(current), (a, b) -> a)); os.stream() .sorted(comparator.orElse((a,b) -> 0)) .forEach(o -> System.out.println(o.getC()));
In this example, I use Optional<Comparator<O>> and the result of shrinking the wrapper with Optional.ofNullable() to handle the case when with an empty list of comparators. Then you can decide when you pass the result to the sorted() method, what to do in the case of an empty list - you can use the comparator (a,b)->0 , which does not sort anything.
Then no matter how many comparators you want to apply. But there is one , but - the order of the comparators in the questions of collection. In this example, I use comparators in ascending order (starting from the first element of the list to the last). This affects the sorting result to a large extent.
For example, in your example, you call byB.thenComparing(byA) . It produces a different result, then byA.thenComparing(byB) . I can assume that in some cases you want to control the order in which comparators are applied.
Live demo:
https://jdoodle.com/a/4Xz
source share