3.1.1 Lambda Syntax Explained
Lambda expressions in Java are a concise way to represent instances of functional interfaces. They allow you to treat functionality as a method argument, or code as data. Understanding the syntax of lambda expressions is crucial for leveraging their power in Java SE 11 applications.
Key Concepts
1. Functional Interface
A functional interface is an interface that contains exactly one abstract method. Lambda expressions can be used to implement these interfaces without the need for a separate class or anonymous inner class.
Example
@FunctionalInterface interface MyFunctionalInterface { void myMethod(); }
2. Lambda Expression Syntax
A lambda expression consists of parameters, an arrow token (->
), and a body. The body can be a single expression or a block of statements.
Example
MyFunctionalInterface myLambda = () -> System.out.println("Hello, Lambda!"); myLambda.myMethod(); // Output: Hello, Lambda!
3. Parameter Types
Lambda expressions can have zero or more parameters. The types of the parameters can be explicitly declared or inferred by the compiler.
Example
interface MyFunctionalInterfaceWithParams { void myMethod(int a, int b); } MyFunctionalInterfaceWithParams myLambda = (a, b) -> System.out.println(a + b); myLambda.myMethod(3, 5); // Output: 8
4. Return Statements
If the body of the lambda expression is a single expression, its value is automatically returned. If the body is a block of statements, you need to use the return
keyword to return a value.
Example
interface MyFunctionalInterfaceWithReturn { int myMethod(int a, int b); } MyFunctionalInterfaceWithReturn myLambda = (a, b) -> { int sum = a + b; return sum; }; System.out.println(myLambda.myMethod(3, 5)); // Output: 8
Examples and Analogies
Think of a lambda expression as a shortcut for writing a method. Instead of defining a method in a class, you can write a lambda expression directly where it is needed. This is similar to using a quick recipe card instead of writing out the entire cookbook.
For example, consider a simple calculator. Instead of defining separate methods for addition, subtraction, etc., you can use lambda expressions to define these operations on the fly.
Example
interface Calculator { int calculate(int a, int b); } Calculator add = (a, b) -> a + b; Calculator subtract = (a, b) -> a - b; System.out.println(add.calculate(10, 5)); // Output: 15 System.out.println(subtract.calculate(10, 5)); // Output: 5
By mastering lambda syntax, you can write more concise and expressive code, making your Java SE 11 applications more readable and maintainable.