Modifying local variable from inside lambda

后端 未结 11 1244
失恋的感觉
失恋的感觉 2020-11-28 04:30

Modifying a local variable in forEach gives a compile error:

Normal

    int ordinal = 0;
    for (Example s : list) {
          


        
11条回答
  •  醉酒成梦
    2020-11-28 05:05

    Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it. Lambdas have been made for functional style of programming and this means: No side effects. What you want to do is considered bad style. It is also dangerous in case of parallel streams.

    You should either find a solution without side effects or use a traditional for loop.

提交回复
热议问题