Lambdas And Functional Interfaces

A lambda expression is a small piece of behavior that can be stored or passed as a value. Its target must be a functional interface with one abstract method.

Function<T, R> represents a transformation from T to R. Java infers the lambda parameter type from that target interface.

Store a tiny behavior

import java.util.function.Function;
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Predicate<String> isLong = word -> word.length() >= 5;
        System.out.println(isLong.test("Java"));
        System.out.println(isLong.test("Kotlin"));

        Function<Integer, Integer> half = n -> n / 2;
        System.out.println(half.apply(10));
    }
}

Output:

false
true
5

The first lambda tests whether a string has at least five characters; a Predicate<T> runs when test invokes it. A Function's single method is apply, which runs the transformation and returns its result.

A lambda can use local variables from the surrounding method only if they are effectively final, meaning nothing reassigns them after their first assignment. If you reassign one, the compiler reports that local variables referenced from a lambda expression must be final or effectively final.

Use a Function lambda to double a value, then apply it to 21.