如何将forEach转换为lambda [英] how to convert forEach to lambda

查看:375
本文介绍了如何将forEach转换为lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Iterator<Rate> rateIt = rates.iterator();
int lastRateOBP = 0;
while (rateIt.hasNext())
{
    Rate rate = rateIt.next();
    int currentOBP = rate.getPersonCount();
    if (currentOBP == lastRateOBP)
    {
        rateIt.remove();
        continue;
    }

    lastRateOBP = currentOBP;
}

我如何使用上面的代码转换为lambda java的流?例如list.stream()。filter().....但我需要操作列表。

how can i use above code convert to lambda by stream of java 8? such as list.stream().filter().....but i need to operation list.

推荐答案

如果你真的希望与您在评论中所说的不同并按照以下简单排序:

If you really want distinct and sorted as you say in your comments, than it is as simple as :

TreeSet<Rate> sorted = rates.stream()
                  .collect(Collectors.toCollection(() -> 
                   new TreeSet<>(Comparator.comparing(Rate::getPersonCount))));

但请注意,在你的迭代器示例中,你不是删除重复项,而只是重复项连续(我在你的问题的评论中举例说明。)

But notice that in your example with an iterator you are not removing duplicates, but only duplicates that are continuous (I've exemplified that in the comment to your question).

编辑

您希望功能 distinct ;或者用简单的话来说你想要 personCount 的不同元素,但是如果发生冲突你想要取 max pos

It seems that you want distinct by a Function; or in simpler words you want distinct elements by personCount, but in case of a clash you want to take the max pos.

在jdk中,尚未这样的东西。但它可能是,请参阅

Such a thing is not yet available in jdk. But it might be, see this.

由于您希望按键排序和区分,我们可以通过以下方式模拟它:

Since you want them sorted and distinct by key, we can emulate that with:

 Collection<Rate> sorted = rates.stream()
            .collect(Collectors.toMap(Rate::getPersonCount,
                    Function.identity(),
                    (left, right) -> {
                        return left.getLos() > right.getLos() ? left : right;
                    },
                    TreeMap::new))
            .values();

    System.out.println(sorted);

另一方面,如果你绝对需要来返回 TreeSet 实际上表示这是唯一元素并已排序:

On the other hand if you absolutely need to return a TreeSet to actually denote that this are unique elements and sorted:

 TreeSet<Rate> sorted = rates.stream()
            .collect(Collectors.collectingAndThen(

                    Collectors.toMap(Rate::getPersonCount,
                            Function.identity(),
                            (left, right) -> {
                                return left.getLos() > right.getLos() ? left : right;
                            },
                            TreeMap::new),
                    map -> {
                        TreeSet<Rate> set = new TreeSet<>(Comparator.comparing(Rate::getPersonCount));
                        set.addAll(map.values());
                        return set;
                    }));

这篇关于如何将forEach转换为lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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