Java Tutorial · Advanced Java · Lesson 31 of 37

Java Lambdas

Lambda expressions, functional interfaces and method references.

Lambda expressions

A lambda is a short anonymous function: (parameters) -> expression. It can be used wherever a functional interface (an interface with one abstract method) is expected:

Example 1
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Lin", "Ada", "Grace"));
        names.sort((a, b) -> a.length() - b.length());
        System.out.println(names);
        names.forEach(n -> System.out.println("Hi " + n));
        names.replaceAll(String::toUpperCase);
        System.out.println(names);
    }
}

Output

[Lin, Ada, Grace]
Hi Lin
Hi Ada
Hi Grace
[LIN, ADA, GRACE]

Run this on your computer — see “Get Started” for setup.

Built-in functional interfaces

Interface Method Shape
Function<T, R> apply T → R
Predicate<T> test T → boolean
Consumer<T> accept T → void
Supplier<T> get () → T
BiFunction<T, U, R> apply (T, U) → R
Example 2
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> doubleIt = x -> x * 2;
        Function<Integer, Integer> plusOne = x -> x + 1;
        Predicate<String> isLong = s -> s.length() > 4;
        Supplier<String> greeting = () -> "Hello!";
        BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b;
        System.out.println(doubleIt.andThen(plusOne).apply(5));
        System.out.println(isLong.test("Java") + " " + isLong.negate().test("Java"));
        System.out.println(greeting.get() + " " + multiply.apply(6, 7));
    }
}

Output

11
false true
Hello! 42

Run this on your computer — see “Get Started” for setup.

Method references

ClassName::method is shorthand for a lambda that just calls a method: String::toUpperCase, System.out::println, Person::new.

Test yourself

What is a functional interface?

  1. An interface with no methods
  2. An interface with exactly one abstract method
  3. A class with static methods
  4. Any interface
Show answer

Answer: An interface with exactly one abstract method