Close

Java 11 - Local-Variable Syntax for Lambda Parameters (JEP 323)

[Last Updated: Dec 13, 2018]

Java 11 allows local 'var' syntax of Java 10 to be used in lambda expressions (JEP 323).

Example

public class VarInLambdaExample {
  public static void main(String[] args) {
      IntStream.of(1, 2, 3, 5, 6, 7)
               .filter((var i) -> i % 3 == 0)
               .forEach(System.out::println);
  }
}
3
6

Without var:

public class WithoutVarInLambdaExample {
  public static void main(String[] args) {
      IntStream.of(1, 2, 3, 5, 6, 7)
               .filter(i -> i % 3 == 0)
               .forEach(System.out::println);
  }
}
3
6

Benefits of using var

One benefit of using 'var' in lambdas is that , type annotations can be applied to local variables without losing brevity:

  (@Nonnull var x, @Nullable var y) -> x.process(y)

Also we can use 'final' with var:

  (final var x) -> Math.pow(x, 4)

Example Project

Dependencies and Technologies Used:

  • JDK 9.0.1
Java 11 - Using 'var' in Lambda Select All Download
  • java-11-lambda-local-var
    • src
      • com
        • logicbig
          • example
            • VarInLambdaExample.java

    See Also