Modifying local variable from inside lambda

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

    Use a wrapper

    Any kind of wrapper is good.

    With Java 8+, use either an AtomicInteger:

    AtomicInteger ordinal = new AtomicInteger(0);
    list.forEach(s -> {
      s.setOrdinal(ordinal.getAndIncrement());
    });
    

    ... or an array:

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

    With Java 10+:

    var wrapper = new Object(){ int ordinal = 0; };
    list.forEach(s -> {
      s.setOrdinal(wrapper.ordinal++);
    });
    

    Note: be very careful if you use a parallel stream. You might not end up with the expected result. Other solutions like Stuart's might be more adapted for those cases.

    For types other than int

    Of course, this is still valid for types other than int. You only need to change the wrapping type to an AtomicReference or an array of that type. For instance, if you use a String, just do the following:

    AtomicReference value = new AtomicReference<>();
    list.forEach(s -> {
      value.set("blah");
    });
    

    Use an array:

    String[] value = { null };
    list.forEach(s-> {
      value[0] = "blah";
    });
    

    Or with Java 10+:

    var wrapper = new Object(){ String value; }
    list.forEach(s->{
      wrapper.value = "blah";
    });
    

提交回复
热议问题