Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Java › Lambdas and streams

Lambda expressions and functional interfaces

When does the code written in a lambda run?

Why it exists — Without lambdas, even to pass just one action, such as the rule for sorting or what to do when a button is pressed, you had to write several lines that implement an interface with an anonymous class. A lambda shortens the implementation of an interface that has only one abstract method to the shape (parameters) -> body, so that you write only the action to pass.

Where it's used today — You use it when you pass an action to a standard method that takes one, such as filter and map of a stream, forEach, removeIf, and sort of a list, and computeIfAbsent of a Map. You also use it to put off creating a value until it is needed, as with orElseGet of Optional, and to make the Runnable you pass to a thread. When the body gets long, you move it out to a named method and pass it with a method reference.

A lambda is syntax that turns "an action to run later" into an object. The body is not run on the line where the lambda is written; it runs when the side that received the object calls it. In this lab you pass lambdas to Java standard methods (forEach, removeIf, and sort of ArrayList, filter and map of a stream, Comparator.comparing, and orElseGet of Optional) and see when and how many times a standard method calls the lambda. The type of a lambda is decided by the parameter type of the method that receives it. Here they are all Consumer, Predicate, Function, and Supplier, which Java provides in the java.util.function package.

Checked against real execution · On the PC used to write this lab, the code on the screen was compiled and run as is on JDK 21 for each of 16 combinations, the order of output, the number of times the lambda body ran, and the result were checked, and the parameter types of the standard methods (reflection) and the lines of JDK source that were copied into this lab were checked

Concepts in this lab

Lambda expression
This is a syntax, introduced in Java 8, for writing a function with no name in a compact way. It has the form (parameters) -> body, and it is used as the implementation of a functional interface, which has only one abstract method. It lets you pass behavior (code) to another method as if it were a value.
Functional interface
Why it exists — Java has no separate type that represents just a function, so a type was needed for the variables and parameters that receive a lambda. A functional interface uses an interface with only one abstract method as that type, so existing interfaces such as Runnable and Comparator can receive a lambda as they are.
Where it's used today — It is used when you write a method that receives behavior as a parameter, as the stream's filter receives a Predicate and map receives a Function. When you define one yourself, you add @FunctionalInterface so that the compiler checks that there is only one abstract method.
This is an interface with only one abstract method (a redeclared method of Object such as equals is not counted, and any number of default and static methods is allowed), and it is a type to which a lambda expression or a method reference can be assigned. The java.util.function package predefines types such as Function (takes an input and returns a result), Supplier (supplies a value), Consumer (consumes a value), and Predicate (tests a condition).
Standard methods that take a lambda
Why it exists — In common jobs such as repeating, filtering, sorting, and creating a default value, the only part that changes is "what to do with one element". The standard library takes care of the rest (the repetition and its order, and when to run), and takes only the changing part as a lambda, so that you do not write the same loop again every time.
Where it's used today — You use them every day in shapes such as list.forEach(System.out::println), list.removeIf(s -> s.isBlank()), list.sort(Comparator.comparing(String::length)), map.computeIfAbsent(key, k -> new ArrayList<>()), optional.orElseGet(() -> loadDefault()), and new Thread(() -> …) (loadDefault is a method name chosen for this example). The parameter type of a method tells you what shape of lambda you have to pass.
These are the methods in the Java standard library whose parameter type is a functional interface, so that you can pass a lambda or a method reference. forEach of ArrayList takes a Consumer and calls accept for each element, and removeIf takes a Predicate and calls test for each element and removes the elements for which true came back. filter of a stream takes a Predicate and map takes a Function, and the terminal operation (toList and so on) calls those lambdas when it sends the elements through. Comparator.comparing takes a Function that takes out a key and makes a Comparator, and that Function is called each time sort compares. orElseGet of Optional takes a Supplier and calls get only when there is no value. When and how many times a lambda is called is decided by these methods that received it.
Method reference
Where it's used today — You often see it in streams and sorting in forms such as map(String::trim), forEach(System.out::println), and Comparator.comparing(String::length). When you process the argument or call a method twice, write a lambda instead.
This is a syntax that refers to an existing method by name in place of a lambda. You write it by joining a class (or an object) and a method name with ::, as in String::length or System.out::println. It is a shorter way to write a lambda that does nothing but call one method.
Stream API
This API expresses filtering, transformation, and aggregation over data such as collections in a declarative way. You chain intermediate operations such as filter and map, and finish with a terminal operation such as collect or forEach. Intermediate operations do not run until the terminal operation is called (lazy evaluation), and a stream does not modify its source data and can be used only once.
Lazy evaluation
Why it exists — If a computation is done immediately, it produces values that end up unused, and every step must store its whole intermediate result. Lazy evaluation removes that waste by delaying the computation until the value is actually used.
Where it's used today — Optional's orElseGet runs the Supplier only when there is no value, and the Logger of java.util.logging, when given a Supplier, does not build the message string if logging at that level is turned off.
This approach delays a computation until its result is actually needed. The intermediate operations of a stream do not run as soon as they are called. They run only when the terminal operation is called, and each element passes through the pipeline one at a time. The stream can process only as much as it needs and then stop. Lazy fetching in JPA follows the same idea: associated data is queried when it is actually used.
orElse and orElseGet
Why it exists — If every time you take a value out of an Optional you write an if statement that checks with isPresent() and then calls get(), the code gets long, and mistakes also happen, such as calling get() without checking. orElse and orElseGet let you write "if it is empty, this" in a single call.
Where it's used today — Use orElse where a fixed default value is used when the setting value is missing, and orElseGet where the DB has to be queried again or a new object has to be created and saved when it is empty. To throw an exception instead of a default value when it is empty, use orElseThrow.
These are the two methods that set the default value to use in its place when an Optional is empty. orElse(value) takes the default value itself as its argument, and orElseGet(function) takes a function (a lambda expression) that produces the default value. Java evaluates the arguments before it calls a method, so if you write orElse(makeDefault()), makeDefault() runs even when the Optional has a value. orElseGet runs the function that it was given only when the Optional is empty. So use orElseGet when creating the default value takes time or when other work, such as saving or logging, happens along with it.
Comparable and Comparator
These are the two ways to define the order of objects. Comparable is an interface that a class implements itself, and its single method, compareTo, defines the natural ordering of that class. A Comparator is a way of comparing that is created separately, outside the class, and it lets you sort the same objects by a different sort key each time. Both return a negative number if the first object comes first, 0 if the order cannot be decided, and a positive number if it comes later. Returning the difference of two numbers as it is can flip the sign through overflow, so use Integer.compare or Comparator.comparingInt.
Differences between anonymous classes and lambda expressions
An anonymous class is syntax that implements an interface or a class right where it is used and creates an object without giving the class a name, and it is written in the form new InterfaceName() { method implementations }. A lambda expression is syntax that does the same thing more briefly, in the form (parameters) -> statement, but only for a functional interface, which has exactly one abstract method. When you implement a functional interface with a simple body that does not use this, the result of a call is the same whichever of the two you use. However, an anonymous class can also implement an interface that has several methods, and it can have fields, and this inside it refers to the object of the anonymous class itself. this inside a lambda expression refers to the enclosing object in which the lambda expression is written.

Try these

Running with the default settings

  1. List<String> names = new ArrayList<>(List.of("kiwi", "fig", "banana")): this creates a Java standard ArrayList whose elements are kiwi, fig, and banana in that order.
  2. System.out.println("Before calling forEach"): the line printed is "Before calling forEach".
  3. names.forEach(n -> …): the lambda creates a Consumer<String> object and passes it to forEach. The parameter type of forEach is Consumer<? super E>, so this lambda implements accept of Consumer. The body does not run at the moment it is passed.
  4. action.accept("kiwi"): The standard ArrayList.forEach calls accept for each element, and only here does the body run. The line printed is "Lambda ran: kiwi".
  5. action.accept("fig"): The same body runs once more with the next element. The line printed is "Lambda ran: fig".
  6. action.accept("banana"): The same body runs once more with the next element. The line printed is "Lambda ran: banana".
  7. System.out.println("forEach done"): the line printed is "forEach done". The body ran 3 times in all.

Result of this run

Code

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("kiwi", "fig", "banana"));
        System.out.println("Before calling forEach");
        names.forEach(n -> System.out.println("Lambda ran: " + n));   // Consumer<String>
        System.out.println("forEach done");
    }
}

Assumptions of this model

For each of the sixteen combinations (8 standard methods × has values or empty), the code on the screen was written as is to Main.java, compiled and run with JDK 21 in the verification environment, and the printed lines and their order, the number of times the body ran, and the result were checked (verify/plain/lambda_probe.js, cmp_lambda.js). The parameter types of the standard methods were checked with reflection, and the lines of code copied into "where the standard method's code calls it" were checked by whether that text is in the JDK 21 source (src.zip). The order and number of comparisons in sorting are what ArrayList.sort (TimSort) of JDK 21 actually showed with these three elements, and they are not set by the Java specification, so they can differ on another JDK or with other elements. The order in which the elements pass through filter and map one at a time was also seen in this sequential stream, and in a parallel stream the order is not fixed. A lambda, an anonymous class, and a method reference give the same result in what this lab shows, but they differ in how the object is created inside and in what this refers to. When a lambda uses a local variable of the enclosing code, it can use only a variable whose value does not change, and this rule is explained in the lab "Inner classes and anonymous classes".

Previous lab: Sorting and Comparator · Next lab: Lazy evaluation in streams

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these