Java MCQ: What does the Local-Variable Syntax for Lambda Parameters in Java 11 allow you to do?
Answer:
Explanation:
The Local-Variable Syntax for Lambda Parameters, introduced in Java 11, allows you to use the var
keyword to declare the types of lambda parameters. This feature provides consistency with local variable declarations, where var
can be used to infer the type. However, all lambda parameters must be either explicitly typed with var
or all must be untyped; a mix of typed and untyped parameters is not allowed.
Here’s an example of using var
in a lambda expression:
import java.util.List;
import java.util.stream.Collectors;
public class VarInLambdaExample {
public static void main(String[] args) {
List<String> names = List.of("John", "Jane", "Jack");
List<String> uppercasedNames = names.stream()
.map((var name) -> name.toUpperCase())
.collect(Collectors.toList());
System.out.println(uppercasedNames);
}
}
In this example, var
is used to declare the type of the lambda parameter name
. The compiler infers that name
is a String
based on the context.
The Local-Variable Syntax for Lambda Parameters enhances code readability and consistency when using var
across different parts of a Java program.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html