Lambda Expressions in Java
A lambda expression in Java is a short block of code that takes parameters and returns a value, written without a name. It is used to pass behavior as an argument to a method, for example "how to compare two students" or "what to do with each element". A lambda provides the implementation of a functional interface, an interface with exactly one abstract method. Lambdas were added in Java 8. In this lesson, you will learn the syntax of lambdas and see where they are used.
Syntax
(parameters) -> expression
(parameters) -> { statements; }- Parameters: zero or more, in parentheses.
- Arrow
->: separates the parameters from the body. - Body: a single expression (its value is returned automatically) or a block in braces (use
returnif a value is needed).
Forms of Lambda Expressions
| Form | Example |
|---|---|
| No parameters | () -> System.out.println("Hi") |
| One parameter (parentheses optional) | n -> n * n |
| Two parameters | (a, b) -> a + b |
| With explicit types | (String a, String b) -> a.length() - b.length() |
With var (Java 11) | (var a, var b) -> a + b |
| Block body | n -> { int sq = n * n; return sq + 1; } |
Example: Lambdas with Functional Interfaces
Let's see an example that stores lambdas in variables and calls them.
public class LambdaDemo {
interface Greeter {
String greet(String name);
}
interface Calculator {
int apply(int a, int b);
}
public static void main(String[] args) {
Greeter hello = name -> "Hello, " + name + "!";
System.out.println(hello.greet("Navika"));
Calculator add = (a, b) -> a + b;
Calculator max = (a, b) -> {
if (a > b) {
return a;
}
return b;
};
System.out.println("3 + 4 = " + add.apply(3, 4));
System.out.println("max(3, 4) = " + max.apply(3, 4));
Runnable task = () -> System.out.println("Task running");
task.run();
}
}Hello, Navika!
3 + 4 = 7
max(3, 4) = 4
Task runningExplanation: Greeter and Calculator each have one abstract method, so a lambda can implement them. The lambda's parameters match the method's parameters, and its body becomes the method body. max uses a block body with return. Runnable is a built-in interface whose run method takes no parameters.
Example: Lambdas Passed to Methods
The most common use of a lambda is as an argument:
import java.util.ArrayList;
import java.util.List;
public class PassLambda {
public static void main(String[] args) {
List<String> names = new ArrayList<>(
List.of("Srihitha", "Navika", "Advitha", "Anamaneni"));
names.sort((a, b) -> a.length() - b.length());
System.out.println("By length: " + names);
names.removeIf(n -> n.startsWith("A"));
System.out.println("Without A names: " + names);
names.forEach(n -> System.out.println("Hi " + n));
}
}By length: [Navika, Advitha, Srihitha, Anamaneni]
Without A names: [Navika, Srihitha]
Hi Navika
Hi SrihithaExplanation: sort takes a lambda that compares two names, removeIf takes a lambda that tests a name, and forEach takes a lambda that acts on each name. Each method receives a small piece of behavior instead of a full class.
Common Mistakes
Using a lambda where the target isn't a functional interface. Object o = () -> {}; doesn't compile; a lambda needs a functional interface type.
Forgetting return in a block body that must return a value. (a, b) -> { a + b; } doesn't compile; write { return a + b; }.
Changing a local variable inside a lambda. Local variables used in a lambda must be effectively final (see "Effectively Final Variables and Lambda Capture").
Interview Corner
What is a lambda expression in Java?
A lambda expression is an anonymous function, written as (parameters) -> body, that provides the implementation of a functional interface's single abstract method. It lets you pass behavior as an argument, for example to sort, forEach or stream operations. Its parameter types are usually inferred from the target interface, and a single-expression body returns its value automatically.
Practice
- Easy: Write a functional interface
Shapewith a methoddouble area(double side), and lambdas for a square's and a circle's area (using the side as the radius). - Harder: Write a method
applyTwice(Calculator c, int x)that returnsc.apply(c.apply(x, x), x), and call it with three different lambdas.
Key Takeaways
Was this tutorial helpful?