Java

Functional Interfaces — Function / Predicate / Consumer / Supplier

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The four core single-method interfaces in `java.util.function`. They're the parameter types for streams, Optional methods, CompletableFuture, and countless library APIs.
Java
Raw
import java.util.function.*;

class Demo {
    void example() {
        // Function<T, R> — takes a T, returns an R
        Function<String, Integer> len = String::length;
        System.out.println(len.apply("hello"));               // 5

        // Compose: andThen / compose
        Function<String, String> upper = String::toUpperCase;
        Function<String, Integer> lengthOfUpper = upper.andThen(len);
        System.out.println(lengthOfUpper.apply("Hi"));        // 2

        // Predicate<T> — takes a T, returns boolean
        Predicate<String> nonEmpty = s -> !s.isEmpty();
        Predicate<String> short_   = s -> s.length() < 10;
        var both = nonEmpty.and(short_);
        var either = nonEmpty.or(short_);
        var inverse = nonEmpty.negate();
        System.out.println(both.test("hello"));               // true

        // Consumer<T> — takes a T, returns nothing (side effect)
        Consumer<String> println = System.out::println;
        println.accept("hi");

        // Supplier<T> — takes nothing, returns a T (factory / lazy producer)
        Supplier<java.util.UUID> uuids = java.util.UUID::randomUUID;
        System.out.println(uuids.get());

        // BiFunction<T, U, R> — two args
        BiFunction<Integer, Integer, Integer> add = Integer::sum;
        System.out.println(add.apply(2, 3));                  // 5
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.