Built-in Functional Interfaces

The Core Four (and Friends)

Package java.util.function has 43 interfaces, but you only need to remember a few. The others are variations for two arguments (Bi...) or primitives (Int..., Long..., Double...) that avoid boxing.

InterfaceMethodTakes → ReturnsTypical use
Supplier<T>get()nothing → Tlazy values, factories
Consumer<T>accept(T)T → nothingprinting, saving, forEach
Function<T,R>apply(T)T → Rmapping, converting
Predicate<T>test(T)T → booleanfiltering, validation
UnaryOperator<T>apply(T)T → Ttransform same type
BinaryOperator<T>apply(T,T)(T,T) → Treduce, merge
BiFunction<T,U,R>apply(T,U)(T,U) → Rtwo inputs
IntPredicate, ToIntFunction<T>test(int), applyAsInt(T)primitive versionsno boxing cost

Using Each One

Example

A small order-processing example that uses each of the core interfaces.

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

public class Main {
    public static void main(String[] args) {
        Supplier<List<Integer>> newCart = ArrayList::new;
        Predicate<Integer> isExpensive = price -> price > 1000;
        Function<Integer, Double> withGst = price -> price * 1.18;
        Consumer<String> log = msg -> System.out.println("[LOG] " + msg);
        UnaryOperator<String> shout = s -> s.toUpperCase();
        BinaryOperator<Integer> max = (a, b) -> a >= b ? a : b;

        List<Integer> cart = newCart.get();
        cart.addAll(List.of(499, 1299, 2599));

        for (int price : cart) {
            if (isExpensive.test(price)) {
                log.accept(price + " with GST = " + withGst.apply(price));
            }
        }
        System.out.println(shout.apply("order placed"));
        System.out.println("Costliest item: " + cart.stream().reduce(max).get());
    }
}

Output

[LOG] 1299 with GST = 1532.82
[LOG] 2599 with GST = 3066.8199999999997
ORDER PLACED
Costliest item: 2599

Primitive Specializations

Function<Integer, Integer> boxes every int into an Integer object. In hot loops prefer IntUnaryOperator, IntPredicate, ToIntFunction and friends.

Example

import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        IntUnaryOperator square = n -> n * n;
        IntPredicate isEven = n -> n % 2 == 0;
        ToIntFunction<String> length = String::length;

        System.out.println(square.applyAsInt(12));
        System.out.println(isEven.test(7));
        System.out.println(length.applyAsInt("Careeroza"));
    }
}

Output

144
false
9