Java 11 - Var in Lambda



Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.

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

Consider the following 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

There are certain limitations on using var in lambda expressions.

  • var parameters cannot be mixed with other parameters. Following will throw compilation error.

(var v1, v2) -> v1 + v2
  • var parameters cannot be mixed with other typed parameters. Following will throw compilation error.

(var v1, String v2) -> v1 + v2
  • var parameters can only be used with parenthesis. Following will throw compilation error.

var v1 -> v1.toLowerCase()
Advertisements