English 中文(简体)
Java 11 - var in lambda
  • 时间:2024-11-05

Java 11 - Var in Lambda


Previous Page Next Page  

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 {}

pubpc class APITester {
   pubpc 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 pmitations 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