Java · Module 9 · Lesson 11 min read

Lambdas & Functional Interfaces

What is a lambda?

A lambda is a short, unnamed function you can pass around like a value.

Java
// Old way: anonymous class
Comparator<String> byLength = new Comparator<String>() {
    public int compare(String a, String b) { return a.length() - b.length(); }
};

// Lambda way ✨
Comparator<String> byLength = (a, b) -> a.length() - b.length();

Lambda syntax

FormExample
No parameters() -> System.out.println("Hi")
One parameterx -> x * 2
Several parameters(a, b) -> a + b
Multi-line body(a, b) -> { int s = a + b; return s; }

Functional interfaces

A lambda needs a target: an interface with exactly one abstract method. Mark it with @FunctionalInterface to let the compiler check.

Built-in ones in java.util.function:

InterfaceTakes → ReturnsExample
Predicate<T>T → booleann -> n > 0
Function<T, R>T → Rs -> s.length()
Consumer<T>T → nothings -> System.out.println(s)
Supplier<T>nothing → T() -> new Random().nextInt()
BiFunction<T, U, R>T, U → R(a, b) -> a * b
UnaryOperator<T>T → Ts -> s.toUpperCase()

Method references ::

A shortcut when a lambda just calls an existing method:

  • s -> System.out.println(s) → System.out::println
  • s -> s.toUpperCase() → String::toUpperCase
  • s -> Integer.parseInt(s) → Integer::parseInt
  • () -> new ArrayList<>() → ArrayList::new

Capturing variables

Lambdas can use local variables from outside, but only if they're effectively final (never reassigned).

Example

Java
import java.util.*;
import java.util.function.*;

public class LambdaLab {
    public static void main(String[] args) {
        List<String> langs = new ArrayList<>(List.of("Java", "Go", "Kotlin", "C"));

        langs.removeIf(s -> s.length() < 2);           // remove "C"
        langs.sort(Comparator.comparing(String::length));
        langs.forEach(System.out::println);            // Go, Java, Kotlin

        Predicate<Integer> isEven = n -> n % 2 == 0;
        Function<Integer, Integer> square = n -> n * n;
        System.out.println(isEven.test(4));            // true
        System.out.println(square.andThen(n -> n + 1).apply(3)); // 10
    }
}