如何链接和应用比较器流? [英] How-to chain and apply a stream of comparators?

查看:69
本文介绍了如何链接和应用比较器流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列未分类的项目和一组比较器。
我想通过使用thenComparing(Multisort)将所有比较器应用到流中
是否有比以下代码更优雅的方式来实现这个?

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 way than the following code to achive this?

Stream unsorted = ...;
Stream<Comparator> comparators = ...;

Comparator compareFunc = comparators.reduce(null, (a, b) -> {
        if(a == null) {
            return b;
        }else {
            return  a.thenComparing(b); 
        }

    });

Stream result = unsorted.sorted(compareFunc);


推荐答案

不要使用标识值 for Comparator s。如果比较器流为空(即不包含任何比较器),则不应排序:

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.

传递给 Optional.map 的方法引用可能需要一些经验才能适应它。所以可能值得使用更详细的lambda语法来显示那里发生的事情:

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<String> 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.

这篇关于如何链接和应用比较器流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆