Java - changing the value of a final variable from within a lambda

前端 未结 3 775
不知归路
不知归路 2021-01-01 03:28

In Java I have the following code

List myList = new ArrayList<>();
for (int i=0;i<9;i++) {
    myList.add(i);
}

Integer sum = 0;

m         


        
3条回答
  •  借酒劲吻你
    2021-01-01 03:34

    Not exactly the answer you are looking for, but in most scenarios you won't need to modify that inside the lambda. This is because it's not idiomatic for lambdas to be state-changing in a proper functional style.

    What you can do to achieve your result is use any of the higher-level functions provided to mask the "accumulator", and then assign:

    sum = myList.stream().mapToInt(x->x).sum();
    

提交回复
热议问题