Java Stream How to - Use effectively final variable








Question

We would like to know how to use effectively final variable.

Answer

import java.util.function.IntUnaryOperator;
/*w  w w  .j av a 2s  . c  om*/
public class Main {
   public static void main(String[] args) {
      Integer number2 = 10;
      // accessed number2 and it's not final inside a lambda
      incrementEffectivelyFinalVar(x -> x + number2);
   }
   public static void incrementEffectivelyFinalVar(IntUnaryOperator operator) {
      System.out.println("operator.applyAsInt(1) = " + operator.applyAsInt(1));
   }

}

The code above generates the following result.