Replace for loop with java 8 foreach for updating values

后端 未结 3 1793
礼貌的吻别
礼貌的吻别 2021-01-15 04:49

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 v         


        
3条回答
  •  旧时难觅i
    2021-01-15 05:05

    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);
    }
    

    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 srcList = Arrays.asList(10, -3, 5), dstList = new ArrayList<>();
    
    int value = 0;
    for(Integer i: srcList) {
        value = i + value/2;
        dstList.add(value);
    }
    

提交回复
热议问题