How-to chain and apply a stream of comparators?

前端 未结 2 638
萌比男神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:34

    Don’t use an identity value for Comparators. If the comparators stream is empty (i.e. does not contain any Comparator) you should not sort:

    Stream result=comparators.reduce(Comparator::thenComparing)
                 .map(unsorted::sorted).orElse(unsorted);
    

    Note that if the comparators stream contains only a single Comparator, that Comparator will be the result of the reduction.


    The method reference passed to Optional.map might need some experience to get used to it. So it might be worth using the more verbose lambda syntax to show what’s going on there:

    Stream result=comparators.reduce(Comparator::thenComparing)
        .map((comparator) -> unsorted.sorted(comparator)).orElse(unsorted);
    

    That’s a matter of programming style or personal preference and might change over time.

提交回复
热议问题