Lambda basics
- Java course
- Intermediate
- Lesson 100/116
- 5 min
Learn lambda expressions with () -> ....
Lambda expression
A lambda expression is a short way to write a small function in one line. The syntax is (parameters) -> body. With no parameters use (); with one parameter the parentheses are optional.
Example: Runnable r = () -> System.out.println("Hello");. This lambda is assigned to a Runnable; when r.run() is called the body executes. A lambda can be assigned to any single-method interface (functional interface); Java infers the type from the method signature.
Functional interface
A lambda can be assigned only to a functional interface, which is an interface with exactly one abstract method. Runnable is an example: it has a single run() method. Java matches the lambda body to that one method.
Interfaces with multiple abstract methods cannot accept a lambda. The @FunctionalInterface annotation warns the compiler; adding a second abstract method becomes a compile error. This keeps lambda assignments safe.
Practice Write a Runnable lambda
Define Runnable r = () -> System.out.println("Hello");. Then call r.run(); to execute the lambda. A single line should print Hello.
Starter code
public class Main {
public static void main(String[] args) {
// Define a Runnable lambda and call run
}
}Sample solution
public class Main {
public static void main(String[] args) {
Runnable r = () -> System.out.println("Hello");
r.run();
}
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the basic syntax of a lambda expression?
- function(parameters) { body }
- (parameters) -> body Correct answer
- def parameters: body
- lambda body end
Explanation: A lambda is written as (parameters) -> body.
2 Complete the no-arg lambda
Runnable r = ____ -> System.out.println("Hello");
Runnable r = () -> System.out.println("Hello");
Explanation: A no-arg lambda starts with ().
3 Match the lambda parts
| Term | Meaning |
|---|---|
() |
No parameters |
-> |
Arrow token |
body |
Code to run |
Runnable |
Single-method interface |