AI Hints
Home›Java Tutorial›Lambdas, Functional Interfaces and Method References
Java · Lesson 100 of 120

Lambdas

Functions as values.

⏱ 2 min read▶ Video at 2:07:38🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A lambda is a small function, without a name, that you can pass around like a value. It lets you hand a piece of behaviour to another method.

  • A small function
  • No name
  • Passed like a value

Lambda syntax

On the left of the arrow are the parameters. On the right is the body, the work to do. With one parameter, you can drop the brackets. With a one line body, there's no return, and no curly braces.

keyvalue
x -> x * 2one parameter
(a, b) -> a + btwo parameters
() -> …no parameters
x -> { …; return y; }a longer body

Lambdas with lists

For each runs a lambda on every item. Here, it prints each name. Sort takes a lambda that compares two names, ignoring case. Remove if removes names longer than three letters. And replace all changes every item. Run it. The names print, then sort alphabetically, then shrink to three, then turn into capitals.

Main.javajava
import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Zoe", "adam", "Mia", "bob"));
        names.forEach(n -> System.out.print(n + " "));
        System.out.println();
        names.sort((a, b) -> a.compareToIgnoreCase(b));
        System.out.println(names);
        names.removeIf(n -> n.length() > 3);
        System.out.println(names);
        names.replaceAll(n -> n.toUpperCase());
        System.out.println(names);
    }
}
Output
Zoe adam Mia bob
[adam, bob, Mia, Zoe]
[bob, Mia, Zoe]
[BOB, MIA, ZOE]

Storing lambdas

A lambda can be stored in a variable. The variable's type says what shape of function it is. Function takes a value, and returns one. Binary operator takes two values of the same type. A longer lambda uses curly braces, and return. Then we call them, with run, and apply. Run it. Hello, eighty one, seven, and sixty.

Main.javajava
import java.util.function.*;
public class Main {
    public static void main(String[] args) {
        Runnable hello = () -> System.out.println("Hello!");
        Function<Integer, Integer> square = x -> x * x;
        BinaryOperator<Integer> add = (a, b) -> a + b;
        Function<Double, Double> withTax = price -> {
            double tax = price * 0.2;
            return price + tax;
        };
        hello.run();
        System.out.println(square.apply(9));
        System.out.println(add.apply(3, 4));
        System.out.println(withTax.apply(50.0));
    }
}
Output
Hello!
81
7
60.0

Summary

A lambda is a small function you can store, and pass around. Parameters, then an arrow, then the body. Next, the types that hold lambdas, functional interfaces.

Key takeaways
  • x -> x * 2
  • Pass behaviour
  • Store in a variable
Next up: Functional Interfaces — the shape of a function