How-to chain and apply a stream of comparators?

前端 未结 2 632
萌比男神i
萌比男神i 2021-02-14 19:49

I have a stream of unsorted items and a stream of comparators. I want to apply all the comparators onto the stream by using \"thenComparing\" (Multisort) Is there a more elegant

2条回答
  •  独厮守ぢ
    2021-02-14 20:28

    Using Mark Peters' suggestion and mixing it with a method reference, you could write your comparator this way:

    Comparator compareFunc = comparators.reduce((a, b) -> 0, Comparator::thenComparing);
    

    Or stealing a bit from Holger instead:

    Optional compareFunc = comparators.reduce(Comparator::thenComparing);
    Stream result = compareFunc.isPresent() ? result.sorted(compareFunc.get())
                                               : unsorted;
    

提交回复
热议问题