用java 8 foreach替换for循环以更新值 [英] Replace for loop with java 8 foreach for updating values

查看:801
本文介绍了用java 8 foreach替换for循环以更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找用优雅的java 8流或lambda解决方案替换以下for循环。有什么简洁和有效的吗?

I'm looking to replace the following for loop with an elegant java 8 stream or lambda solution. Is there anything concise and efficient?

    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<>( Arrays.asList( 10,-3,5));

        // add 1/2 of previous element to each element
        for(int i =1 ;i < myList.size();  ++i )
            myList.set(i, myList.get(i)+myList.get(i-1)/2);

        // myList.skip(1).forEach( e -> e + prevE/2 );  // looking for something in this spirit
    }


推荐答案

您的循环评估依赖于先前评估的结果。它相当于

Your loop evaluation has a dependency to the result of the previous evaluation. It is equivalent to

for(int i = 1, value = myList.get(0); i < myList.size(); i++ ) {
    value = myList.get(i) + value/2;
    myList.set(i, value);
}

使用Stream API或lambda表达式没有真正的简化。事实上,我更喜欢上面显示的变体,即使它更大而不是更小,因为它清楚地说明了实际发生的事情(并且可以通过避免多个 List 来提高效率。查找)。

There is no real simplification by using the Stream API or lambda expressions possible. In fact, I would prefer the variant shown above, even if it’s bigger rather than smaller, as it makes clear what actually happens (and may be slightly more efficient by avoiding multiple List lookups).

如果您创建新的列表,它还允许您编程位置无关:

It also allows you to program position independent, if you create a new List:

List<Integer> srcList = Arrays.asList(10, -3, 5), dstList = new ArrayList<>();

int value = 0;
for(Integer i: srcList) {
    value = i + value/2;
    dstList.add(value);
}

这篇关于用java 8 foreach替换for循环以更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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