Close

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

[Updated: Sep 30, 2018, Created: Sep 30, 2018]

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

This change is introduced to be consistent with the local 'var' syntax of Java 10.

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

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)

Example Project

Dependencies and Technologies Used:

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

    See Also