How-to chain and apply a stream of comparators?

前端 未结 2 2112
不思量自难忘°
不思量自难忘° 2021-02-14 20:20

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:52

    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;
    

提交回复
热议问题