Java Stream How to - Verify that Lambda uses variable value during the calculation








Question

We would like to know how to verify that Lambda uses variable value during the calculation.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
/*w  w  w.  jav a2  s  .  c om*/
public class Main {
  public static void main(String[] args) {
    List<Integer> l = Arrays.asList(1, 3, 2, 4);
    l.forEach(getConsumer(10));
  }

  public static Consumer<Integer> getConsumer(int multiplier) {
    IntWrapper iWrapper = new IntWrapper(10); 
    Consumer<Integer> lambdaToReturn = x -> {
      System.out.println(x * iWrapper.getInt() * multiplier);
    };
    iWrapper.incr(); // Even we increment it later,  lambda still get 11
                     // instead of 10
    return lambdaToReturn;
  }

}

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.