logo

Var In Lambda


Show

Use of var in Lambda expression is allowed in Java 11 and it can make use of apply modifiers to local variables.

(@NonNull var value1, @Nullable var value2) -> value1 + value2

Examine the following given example:

ApiTester.java

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@interface NonNull {}

public class APITester {
   public static void main(String[] args) {
      List<String> tutorialsList = Arrays.asList("Java", "HTML");

      String tutorials = tutorialsList.stream()
         .map((@NonNull var tutorial) -> tutorial.toUpperCase())
         .collect(Collectors.joining(", "));

      System.out.println(tutorials);
   }
}

Output

Java
HTML

Limitations

On using var in lambda expression there are some limitations:

  • var parameters must not be mixed with some other parameters. Below the equation will throw a compilation error.
(var v1, v2) -> v1 + v2
  • var parameters must not be mixed with some other typed parameters. Below the equation will throw a compilation error.
(var v1, String v2) -> v1 + v2
  • var parameters can only be made in use with parenthesis. Below the equation will throw a compilation error.
var v1 -> v1.toLowerCase()