Java Stream How to - Use effectively final object local variable inside Lambda








Question

We would like to know how to use effectively final object local variable inside Lambda.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
//  w  ww .  j  a  v  a  2s  . c  o m
public class Main {
  public static void main(String[] args) {
    List<Integer> l = Arrays.asList(1, 3, 2, 4, 7, 8, 9, 6, 5);
    IntWrapper variableOutside = new IntWrapper(50);
    Consumer<Integer> consumer = i -> {
      int variableInside = 70;
      System.out.println(variableOutside.getInt());
      variableOutside.incr(); // Imagine multi-thread environment calling this
      variableInside++;
      System.out.printf("%s plus %d plus %d equals %d\n", variableOutside,
          variableInside, i, variableOutside.getInt() + variableInside + i);
    };
    variableOutside.incr(); // Now it's the variableOutside starts from 51
    l.forEach(consumer);
  }
}
class IntWrapper {
  private int data;

  public IntWrapper(int i) {
    this.data = i;
  }

  public String toString() {
    return this.data + "";
  }

  public void incr() {
    this.data++;
  }

  public int getInt() {
    return this.data;
  }
}

The code above generates the following result.