Modifying local variable from inside lambda

后端 未结 11 1230
失恋的感觉
失恋的感觉 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:44

    If you only need to pass the value from the outside into the lambda, and not get it out, you can do it with a regular anonymous class instead of a lambda:

    list.forEach(new Consumer() {
        int ordinal = 0;
        public void accept(Example s) {
            s.setOrdinal(ordinal);
            ordinal++;
        }
    });
    

提交回复
热议问题