A lambda expression provides a concise implementation of a functional interface. A functional interface has one abstract method.
In this example, you will use a lambda expression to greet someone by name.
Source code
Save the following code as LambdaExample.java:
public class LambdaExample {
void main() {
Greeting greeting = name -> "Hello, " + name + "!";
IO.println(greeting.greet("Alice"));
IO.println(greeting.greet("Bob"));
}
}
@FunctionalInterface
interface Greeting {
String greet(String name);
}
Explanation
The Greeting interface declares one abstract method:
@FunctionalInterface
interface Greeting {
String greet(String name);
}
The method accepts a name and returns a greeting.
The @FunctionalInterface annotation lets the compiler check that the interface meets the requirements of a functional interface.
Creating the lambda expression
The following statement assigns a lambda expression to a Greeting variable:
Greeting greeting = name -> "Hello, " + name + "!";
Each part has a purpose:
| Part | Purpose |
|---|---|
name |
Receives the method argument |
-> |
Separates the parameter from the body |
"Hello, " + name + "!" |
Produces the returned value |
The compiler knows that name is a String because the greet() method declares a String parameter.
For a single parameter with an inferred type, parentheses are optional. You can also write:
Greeting greeting = (name) -> "Hello, " + name + "!";
Returning a value
This lambda has an expression body:
name -> "Hello, " + name + "!"
The expression’s result is returned automatically. You do not need braces or a return statement.
If you use a block body instead, you must return the value explicitly:
Greeting greeting = name -> {
return "Hello, " + name + "!";
};
Both forms provide the same behavior.
Calling the implementation
Call the interface method through the variable:
greeting.greet("Alice")
This passes "Alice" to the lambda and returns "Hello, Alice!". The program then prints the returned string using IO.println().
Run the example
Compile and run the file:
javac LambdaExample.java
java LambdaExample
Output
Hello, Alice!
Hello, Bob!
A lambda expression needs a target functional interface, such as Greeting in this example. You can also use lambdas with standard functional interfaces from java.util.function, including Predicate, Function, and Consumer.
