Java Stream How to - Use Effectively Final Variables








Question

We would like to know how to use Effectively Final Variables.

Answer

import java.util.function.IntUnaryOperator;
/*  www.  j a v a 2s.  c om*/
public class Main {
   public static void main(String[] args) {
      final Integer number1 = 20;
      Integer number2 = 10;

      MessagePrinter printer = new MessagePrinter() {
         @Override
         public void print() {
            // number1 has to be final
            System.out.println("number1 = " + number1);
         }
      };

      // watch here, we accessed number2 and it's not final inside a lambda
      incrementEffectivelyFinalVar(x -> x + number2);
      printer.print();
   }

   public static void incrementEffectivelyFinalVar(IntUnaryOperator operator) {
      System.out.println("operator.applyAsInt(1) = " + operator.applyAsInt(1));
   }
}
interface MessagePrinter {
  void print();
}

The code above generates the following result.