Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Lambda Syntax: A Practical Guide

Understand Java lambda syntax with practical code examples: functional interfaces, target typing, effectively final variables, method references, and common mistakes.

~4 min readJava
#java#lambda#functional-interface#method-reference
A Java lambda expression shown as an arrow transforming an input into an output, with functional interface concept in the background.

A lambda expression in Java has a compact syntax: (parameters) -> expression or (parameters) -> { statements; }. A lambda is a concise way to supply an implementation of a functional interface—an interface with exactly one abstract method. The compiler uses that interface as the lambda's target type. This article explains the syntax rules, type inference, variable capture, method references, and common mistakes.

Lambda Syntax Basics

The minimal lambda has three parts: a parameter list, an arrow token (->), and a body. The parameter list can be empty, a single parameter without parentheses, or multiple parameters with parentheses. The body can be a single expression or a block with braces.

java
// No parameters () -> System.out.println("Hello"); // Single parameter, parentheses optional name -> System.out.println(name); // Multiple parameters (a, b) -> a + b; // Block body with return (int x) -> { return x * 2; };

The expression form is implicitly returned. In the block form, a lambda that returns a value needs an explicit return statement; a block that completes without returning is void-compatible.

Functional Interfaces: The Target Type

A lambda expression cannot exist on its own. The compiler needs a functional interface—an interface with exactly one abstract method—to assign the lambda to. This is called the target type. The lambda's parameter types and return type must match that abstract method's signature.

java
@FunctionalInterface interface IntAdder { int apply(int a, int b); } IntAdder add = (a, b) -> a + b;

The @FunctionalInterface annotation is optional but documents intent. It causes a compile error if the interface does not have exactly one abstract method. Java's standard java.util.function package provides common functional interfaces like Function, Predicate, Consumer, and Supplier, so you rarely need to define your own.

Type Inference and Target Typing

The compiler infers lambda parameter types from the target type. In the previous example, (a, b) are inferred as int because IntAdder.apply declares two int parameters. This inference works in assignment contexts, method arguments, and return statements.

java
List<String> names = Arrays.asList("Alice", "Bob"); names.stream() .map(name -> name.toUpperCase()) // name inferred as String .forEach(System.out::println);

The target type can become ambiguous when a method is overloaded with different functional interfaces. In that case, the compiler cannot decide which overload to use. A cast or a separate variable of the intended functional interface type can resolve the ambiguity.

Capturing Variables: Effectively Final

A lambda can access variables from the enclosing scope, but only if they are effectively final—not reassigned after initialization. This rule applies to local variables and method parameters. Instance and static fields can be mutated because they are accessed through the enclosing object reference.

java
int base = 10; Function<Integer, Integer> addBase = x -> x + base; // valid base = 20; // compile error: base is not effectively final

The effectively final rule exists because lambdas capture variables by value, not by reference. If the variable could change, the lambda would see an inconsistent value. This is similar to the restriction on anonymous inner classes, but the compiler now checks the variable's usage rather than requiring the explicit final keyword.

Method References as Shorthand

Method references are a condensed form of lambda syntax when the body simply calls an existing method. There are four kinds: static method, instance method of a particular object, instance method of an arbitrary object of a specific type, and constructor.

java
// Static method Function<String, Integer> parseInt = Integer::parseInt; // Instance method of a particular object String prefix = "Mr. "; Function<String, String> addPrefix = prefix::concat; // Instance method of an arbitrary object of a specific type Function<String, String> toLower = String::toLowerCase; // Constructor Supplier<List<String>> listFactory = ArrayList::new;

The compiler checks that the method reference matches the functional interface's signature. A method reference is often more readable than the equivalent lambda, but it is not always shorter. Use it when it directly expresses the intent without obscuring the logic.

Common Syntax Mistakes

Parentheses around a single parameter are optional, so x -> ... and (x) -> ... are both valid; this is a style choice, not an error. If you write a parameter type, parentheses are required: (int x) -> ... is valid, int x -> ... is not.

The real errors come from mixing expression and block forms.

java
// Invalid: return is a statement, not an expression (int x) -> return x * 2; // Invalid: x * 2; is not a valid statement expression by itself (int x) -> { x * 2; } // Valid expression body (int x) -> x * 2; // Valid block body (int x) -> { return x * 2; };

Variable capture errors are also common. If you try to reassign a captured local variable, the compiler reports local variables referenced from a lambda expression must be final or effectively final. The fix is to use a new variable or restructure the logic to avoid mutation.

Runtime Behavior and Performance

Lambdas use invokedynamic rather than compiling a separate anonymous class for every expression. At runtime, the LambdaMetafactory bootstrap method creates the functional interface implementation. Non-capturing lambdas can be represented by a singleton and reused. Capturing lambdas create a new instance when the lambda expression is evaluated, and captured values are stored in that object.

Capturing many variables can therefore increase memory use. In tight loops, creating a new lambda repeatedly may add allocation pressure, but the JIT compiler can often inline the lambda body and eliminate the allocation entirely. There is no inherent performance penalty for using lambdas over traditional loops. If you are writing performance-critical code, measure rather than assume. The readability and maintainability benefits usually outweigh micro-optimizations.

Choosing Between Lambda and Anonymous Class

Lambdas are not a complete replacement for anonymous inner classes. An anonymous class can implement an interface with multiple methods, access instance fields directly, and have its own instance initialization. A lambda can only implement a functional interface and cannot declare fields or have initialization blocks.

Use a lambda when the behavior is a single operation that fits the functional interface contract. Use an anonymous class when you need mutable instance state, multiple methods, or a more complex implementation.

java
// Lambda for simple comparison Comparator<Person> byAge = (p1, p2) -> Integer.compare(p1.age, p2.age); // Anonymous class when state is needed Comparator<Person> byNameWithCache = new Comparator<Person>() { private final Map<String, Integer> cache = new HashMap<>(); @Override public int compare(Person p1, Person p2) { return cache.computeIfAbsent(p1.name, String::length) .compareTo(cache.computeIfAbsent(p2.name, String::length)); } };

The decision is about whether the implementation is a stateless function or a stateful object. Lambdas have no instance fields, but they can capture effectively final variables. If you need mutable instance state, an anonymous class is the right tool.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.