Modifying local variable from inside lambda

后端 未结 11 1247
失恋的感觉
失恋的感觉 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 04:55

    An alternative to AtomicInteger (or any other object able to store a value) is to use an array:

    final int ordinal[] = new int[] { 0 };
    list.forEach ( s -> s.setOrdinal ( ordinal[ 0 ]++ ) );
    

    But see the Stuart's answer: there might be a better way to deal with your case.

提交回复
热议问题