← Learning Hub
Beginner

Lambda Expressions

A lambda is a short way to write a small function. It was the biggest Java 8 feature.

Before Java 8, passing a small piece of behaviour (like "how to compare two products") required a whole anonymous class - five or six lines of boilerplate. A lambda says the same thing in one line. This made Java code much shorter and opened the door to the Stream API.

Think of a lambda as a function you can store in a variable or pass to another method. On the left of the arrow are the inputs, on the right is what to do with them. Java works out the types from the context, so you rarely need to write them.

Example
// parameters  ->  body
(a, b) -> a + b
price -> price * 0.9
() -> System.out.println("Hi")

A lambda can be used wherever a functional interface is expected: an interface with exactly one abstract method. Java 8 gives you ready-made ones in java.util.function:

  • Predicate<T>: takes a value, returns true/false (test).
  • Function<T,R>: takes a value, returns another (apply).
  • Consumer<T>: takes a value, returns nothing (accept).
  • Supplier<T>: takes nothing, returns a value (get).

These four interfaces cover most everyday needs: checking something (Predicate), converting something (Function), doing something with a value (Consumer) and producing a value (Supplier). Many Java library methods accept them, so once you know these, you can pass lambdas almost everywhere.

Example
You can edit this code.

Method references

When a lambda only calls one method, you can write it shorter with :::

Example
List<String> items = Arrays.asList("Pen", "Book");
items.forEach(s -> System.out.println(s));
items.forEach(System.out::println);     // same thing
Key points
  • A lambda is a short anonymous function: (params) -> body.
  • It can be used wherever a functional interface (one abstract method) is expected.
  • Predicate, Function, Consumer and Supplier are the common ones.
  • Method references like System.out::println are an even shorter form.

📝 Test yourself

1. How many abstract methods does a functional interface have?
2. Which functional interface returns true or false?
3. Fill in the arrow that separates lambda parameters from the body:
x x * 2