Java Lambda Expressions and Functional Interfaces
Learn Java lambda expressions from scratch: why lambdas exist, every syntax form (inferred types, block bodies, no parameters, var, unnamed _), functional interfaces and @FunctionalInterface, java.util.function types like Predicate, Supplier and BiFunction, and primitive specializations.
kvi5hnuCode Sprout team member13 min readOn this page
A lambda expression is a block of code that you can pass around, so it can be executed later, once or many times. Lambdas arrived in Java 8 and changed the way Java code is written: the collections API, streams, Optional, CompletableFuture, and countless frameworks are designed around them. This article covers the syntax and the key concept that makes lambdas work in Java: functional interfaces.
Why Lambdas?
Before looking at the syntax (or the curious name), let's see where we've already passed blocks of code around in Java.
In the callbacks article, you did work at timed intervals by putting it into the actionPerformed method of an ActionListener:
class Worker implements ActionListener {
public void actionPerformed(ActionEvent event) {
// do some work
}
}
To run this code repeatedly, you constructed a Worker and submitted it to a Timer. The key point is that actionPerformed contains code you want to execute later.
Or consider sorting with a custom comparator. To sort strings by length, you passed a Comparator object to sort:
class LengthComparator implements Comparator<String> {
public int compare(String first, String second) {
return first.length() - second.length();
}
}
. . .
Arrays.sort(strings, new LengthComparator());
compare isn't called right away. The sort method keeps calling it, rearranging elements that are out of order, until the array is sorted. You give sort the snippet of code it needs to compare elements, and that code is integrated into sorting logic you wouldn't care to reimplement.
Both examples have something in common: a block of code was passed to someone (a timer, or a sort method) and called at some later time.
Before Java 8, giving someone a block of code wasn't easy. Java is object-oriented, so you had to construct an object of a class with a method containing the desired code. Other languages let you work with blocks of code directly. Java's designers resisted adding the feature for a long time, because a great strength of Java is its simplicity and consistency, and a language can become an unmaintainable mess if it includes every feature that yields marginally more concise code. But in those other languages it isn't just easier to spawn a thread or register a click handler: large parts of their APIs are simpler, more consistent and more powerful. Java could have had similar APIs taking objects of interfaces, but they would have been unpleasant to use. So the question became not whether to add functional programming to Java, but how. It took years of experimentation (Project Lambda) before a design emerged that fit Java well.
The Syntax of Lambda Expressions
Consider the sorting example again. We pass code that checks whether one string is shorter than another, computing
first.length() - second.length()
What are first and second? Strings. Java is strongly typed, so we say so as well:
(String first, String second)
-> first.length() - second.length()
That's your first lambda expression: a block of code, together with the specification of the variables that must be passed to it.

Expression bodies and block bodies
The simplest form is: parameters, the -> arrow, and an expression. If the computation doesn't fit in a single expression, write it exactly like a method body, in braces with explicit return statements:
(String first, String second) -> {
if (first.length() < second.length()) return -1;
else if (first.length() > second.length()) return 1;
else return 0;
}
No parameters
If a lambda has no parameters, supply empty parentheses, just as for a parameterless method:
() -> { for (int i = 100; i >= 0; i--) System.out.println(i); }
Inferred parameter types
If the parameter types can be inferred, omit them:
Comparator<String> comp
= (first, second) // same as (String first, String second)
-> first.length() - second.length();
The compiler deduces that first and second are strings because the lambda is assigned to a string comparator. Inferred types are by far the most common style.
A single parameter
If there's exactly one parameter with an inferred type, you can even omit the parentheses:
ActionListener listener = event ->
System.out.println("The time is " + Instant.ofEpochMilli(event.getWhen()));
// instead of (event) -> . . . or (ActionEvent event) -> . . .
Result type
You never specify the result type of a lambda. It's always inferred from context. (String first, String second) -> first.length() - second.length() can be used wherever a result of type int is expected.
var and unnamed parameters
You can write var for an inferred parameter type. That's not common: the syntax exists so you can attach annotations (see the annotations part), which requires some type token:
(@NonNull var first, @NonNull var second) -> first.length() - second.length()
If you use var for one parameter, you must use it for all of them. You can't mix var, explicit types and bare names.
Since Java 22, a parameter that's never used can be written as an underscore _ (it was a preview feature in Java 21):
ActionListener listener = _ -> System.out.println("Tick");
Comparator<String> comp = (_, _) -> 0;
Here's a program that uses lambdas for comparators and other interfaces. (A desktop version with a Swing timer would add new Timer(1000, event -> System.out.println("The time is " + new Date())), which needs a desktop.)
import java.time.LocalDate;
import java.util.*;
import java.util.function.*;
public class Solution {
public static void main(String[] args) {
var planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune" };
System.out.println(Arrays.toString(planets));
System.out.println("Sorted in dictionary order:");
Arrays.sort(planets);
System.out.println(Arrays.toString(planets));
System.out.println("Sorted by length:");
Arrays.sort(planets, (first, second) -> first.length() - second.length());
System.out.println(Arrays.toString(planets));
// a lambda with a block body and explicit parameter types
Comparator<String> byLengthDesc = (String first, String second) -> {
if (first.length() < second.length()) return 1;
else if (first.length() > second.length()) return -1;
else return 0;
};
Arrays.sort(planets, byLengthDesc);
System.out.println(Arrays.toString(planets));
// no parameters: empty parentheses
Runnable countdown = () -> {
for (int i = 3; i >= 1; i--) System.out.print(i + " ");
System.out.println("liftoff");
};
countdown.run();
// one inferred parameter: parentheses optional
Consumer<String> greeter = name -> System.out.println("Hello, " + name);
greeter.accept("Ada");
// var for parameters (useful for annotations), _ for unused parameters (Java 22)
BinaryOperator<Integer> add = (var x, var y) -> x + y;
Comparator<String> allEqual = (_, _) -> 0;
System.out.println(add.apply(2, 3) + " " + allEqual.compare("a", "b"));
// the same code block in different functional interfaces
BiFunction<String, String, Integer> comp = (first, second) -> first.length() - second.length();
System.out.println(comp.apply("Mars", "Jupiter"));
// Predicate: removeIf
var list = new ArrayList<>(Arrays.asList("a", null, "b", null, "c"));
list.removeIf(e -> e == null);
System.out.println(list);
// Supplier: lazy defaults
LocalDate day = null;
LocalDate startDate = Objects.requireNonNullElseGet(day, () -> LocalDate.of(1970, 1, 1));
System.out.println(startDate);
// primitive specializations: Arrays.setAll(int[], IntUnaryOperator)
var values = new int[10];
Arrays.setAll(values, i -> i * i);
System.out.println(Arrays.toString(values));
// your own functional interface
Validator notBlank = s -> !s.isBlank();
Validator shortText = s -> s.length() <= 5;
System.out.println(notBlank.and(shortText).validate("Java") + " "
+ notBlank.and(shortText).validate("Lambda!"));
// a lambda is converted to an object of some class implementing the interface
Runnable r = () -> { };
System.out.println(r instanceof Runnable);
}
}
@FunctionalInterface
interface Validator {
boolean validate(String s); // the single abstract method
default Validator and(Validator other) { // defaults don't count
return s -> validate(s) && other.validate(s);
}
boolean equals(Object obj); // Object methods don't count either
}
[Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune]
Sorted in dictionary order:
[Earth, Jupiter, Mars, Mercury, Neptune, Saturn, Uranus, Venus]
Sorted by length:
[Mars, Earth, Venus, Saturn, Uranus, Jupiter, Mercury, Neptune]
[Jupiter, Mercury, Neptune, Saturn, Uranus, Earth, Venus, Mars]
3 2 1 liftoff
Hello, Ada
5 0
-3
[a, b, c]
1970-01-01
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
true false
true
Functional Interfaces
Java has many existing interfaces that encapsulate blocks of code, such as ActionListener and Comparator. Lambdas are compatible with these interfaces: you can supply a lambda wherever an object of an interface with a single abstract method is expected. Such an interface is called a functional interface.
To see the conversion, consider Arrays.sort. Its second parameter needs a Comparator, an interface with a single abstract method. Simply supply a lambda:
Arrays.sort(words, (first, second) -> first.length() - second.length());
Behind the scenes, Arrays.sort receives an object of some class that implements Comparator<String>. Calling compare on that object executes the lambda's body. How these objects and classes are managed is completely implementation-dependent, and it can be much more efficient than traditional inner classes. (The JVM generates the class at runtime through the invokedynamic instruction and LambdaMetafactory, and a non-capturing lambda is typically a single shared instance.) It's best to think of a lambda as a function, not an object, and to accept that it can be passed to a functional interface.
This conversion is what makes lambdas so compelling. The syntax is short and simple. Compare the timer example:
var timer = new Timer(1000, event -> {
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
Toolkit.getDefaultToolkit().beep();
});
That's a lot easier to read than a separate class implementing ActionListener.
In fact, conversion to a functional interface is the only thing you can do with a lambda in Java. Other languages with function literals have function types such as (String, String) -> int, and let you declare variables of those types. The Java designers chose to stick with the familiar concept of interfaces instead of adding function types. A lambda has no type of its own: the target type of the context decides what it becomes. You can't even assign a lambda to a variable of type Object, because Object isn't a functional interface (incompatible types: Object is not a functional interface).
@FunctionalInterface
When you design your own functional interface, tag it with the @FunctionalInterface annotation. It has two advantages:
- The compiler gives an error if you accidentally add a second abstract method (or have none).
- The javadoc page states that the interface is functional.
The annotation isn't required: by definition, any interface with a single abstract method is functional. But using it is good practice. The Validator interface in the demo shows that defaults and redeclared Object methods are allowed alongside the one abstract method.
Function Types in java.util.function
The java.util.function package defines a set of very generic functional interfaces. For example, BiFunction<T, U, R> describes functions with parameter types T and U and return type R. You can save the string comparison lambda in a variable of that type:
BiFunction<String, String, Integer> comp
= (first, second) -> first.length() - second.length();
But that doesn't help you sort: there's no Arrays.sort that wants a BiFunction. If you've used a functional language, this may seem curious. For Java programmers, it's natural: an interface such as Comparator has a specific purpose, not just a method with given parameter and return types. When you want to do something with a lambda, keep its purpose in mind and use a specific functional interface for it.
Here are the generic interfaces you'll meet most often. The lambda scope and comparators article has the complete tables.
| Interface | Abstract method | Typical use |
|---|---|---|
Runnable | void run() | Run an action, e.g. in a thread |
Supplier<T> | T get() | Lazily produce a value |
Consumer<T> | void accept(T t) | Do something with a value |
Function<T, R> | R apply(T t) | Transform a value |
BiFunction<T, U, R> | R apply(T t, U u) | Combine two values |
UnaryOperator<T> / BinaryOperator<T> | T apply(T t) / T apply(T t, T u) | Same type in and out |
Predicate<T> | boolean test(T t) | Filter or check a condition |
Predicate
A particularly useful one is Predicate:
public interface Predicate<T> {
boolean test(T t);
// additional default and static methods
}
ArrayList has a removeIf method whose parameter is a Predicate, designed specifically for passing a lambda. This statement removes all null values from an array list:
list.removeIf(e -> e == null);
Supplier and lazy evaluation
A Supplier<T> has no parameters and yields a value of type T when called:
public interface Supplier<T> {
T get();
}
Suppliers are used for lazy evaluation. Consider
LocalDate startDate = Objects.requireNonNullElse(day, LocalDate.of(1970, 1, 1));
That's not optimal. We expect day to be rarely null, so we only want to construct the default LocalDate when necessary. With a supplier, the computation is deferred:
LocalDate startDate = Objects.requireNonNullElseGet(day, () -> LocalDate.of(1970, 1, 1));
requireNonNullElseGet calls the supplier only when the value is needed. You'll see the same pattern in Optional.orElseGet, Map.computeIfAbsent and logging APIs such as logger.fine(() -> "expensive " + message).
Primitive specializations
Functional interfaces that involve primitive types are a little cumbersome. A function consuming an int and yielding a T could be a Function<Integer, T>, but then the argument is boxed on every call. Instead there's IntFunction<T>. Conversely, for an int result, ToIntFunction<T> is more efficient than Function<T, Integer>. If both argument and result are int, there's IntUnaryOperator. Similar interfaces exist for long and double.
As the user of an API, you usually don't care about this subtlety. Arrays.setAll sets every element of an array to the result of a function of the index:
var values = new int[100];
Arrays.setAll(values, i -> i * i); // [0, 1, 4, 9, 16, ...]
There are overloads of setAll for int[], long[], double[] and generic T[]. The int[] version takes an IntUnaryOperator, but you just supply the lambda, without worrying about primitive types versus wrappers.
Common questions
Is a lambda an object? At runtime, a lambda becomes an object of a class that implements the target functional interface. That class is generated by the JVM, and a lambda that captures nothing is usually one shared instance. In the language, though, a lambda has no type of its own. It only becomes something when the context gives it a functional interface type.
Can a lambda throw a checked exception?
Only if the functional interface's method declares it. Callable<T> allows throws Exception, while Runnable, Function and the other java.util.function interfaces don't. To call I/O code inside a stream lambda, catch the exception and wrap it (for example in UncheckedIOException), or define your own functional interface that declares the exception.
Are lambdas slower than anonymous classes?
No, usually the opposite. Lambdas don't need a separate class file, they are linked lazily with invokedynamic, and non-capturing ones are cached. In hot code the JIT inlines them like ordinary methods.
Can I use a lambda where an abstract class is expected? No. Only interfaces with a single abstract method are functional interfaces. For an abstract class, write an anonymous subclass, or add a static factory method to the class that takes a lambda.
How do I write a recursive lambda?
A lambda can't refer to itself by name. Use a normal method (and a method reference to it if you need a functional object), or store the lambda in a field and refer to the field by its qualified name: static IntUnaryOperator fact = n -> n <= 1 ? 1 : n * Solution.fact.applyAsInt(n - 1);. (With the plain name fact, javac rejects the code as a self-reference in initializer.) In practice a private method is clearer.
Summary
- A lambda expression is a block of code with parameters:
(params) -> expressionor(params) -> { statements }. - Parameter types can usually be inferred. A single inferred parameter needs no parentheses, no parameters need
(),varenables annotations, and_marks unused parameters (Java 22). The result type is always inferred. - A functional interface has exactly one abstract method. Default, static and redeclared
Objectmethods don't count. Mark your own with@FunctionalInterface. - A lambda can only be converted to a functional interface. Its target type decides what it becomes, and
Objectisn't allowed. java.util.functionprovides general-purpose interfaces:Supplier,Consumer,Function,BiFunction,Predicate, operators, and primitive specializations such asIntUnaryOperator. Prefer purpose-specific interfaces such asComparatorwhen one exists.
Practice Questions
Write a lambda that sorts a String[] words in reverse dictionary order with Arrays.sort.
Arrays.sort(words, (a, b) -> b.compareTo(a));
Which of these are valid lambdas? (a) x -> x * 2 (b) (int x, y) -> x + y (c) () -> 42 (d) (var a, var b) -> a + b
(a), (c) and (d) are valid. (b) is invalid, because you can't mix an explicitly typed parameter with an inferred one.
Is this a functional interface? interface Shape { double area(); default double perimeter() { return 0; } String toString(); }
Yes. It has exactly one abstract method, area. The default method and the redeclared Object method toString don't count.
Why doesn't Object o = () -> {}; compile, while Runnable r = () -> {}; Object o = r; does?
A lambda needs a functional interface as its target type, and Object isn't one. Once the lambda has become a Runnable object, that object can be assigned to Object like any other.
Rewrite list.removeIf(new Predicate<String>() { public boolean test(String s) { return s.isBlank(); } }) with a lambda.
list.removeIf(s -> s.isBlank()); (or list.removeIf(String::isBlank); with a method reference, covered in the next article).
Why use Objects.requireNonNullElseGet(x, () -> createDefault()) instead of requireNonNullElse(x, createDefault())?
With requireNonNullElse, createDefault() is evaluated on every call, even when x isn't null. The supplier version calls it only when needed, which matters if creating the default is expensive.
Related reading
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
- Java Optional: Getting, Consuming and Transforming Optional Values

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.