Functional Programming Patterns in Java

Java is not a functional language, but since Java 8 its functions are values: they can be stored, passed, returned and combined. This page explains how lambdas work underneath, then shows composition, higher-order functions, currying and memoization, Optional and an Either type, design patterns written as functions, and the traps and costs to know about.

Contents

Functions as values in Java

Functional programming treats functions as values: they can be stored in variables, passed to methods, returned from methods and combined into new functions. It also prefers pure functions, whose result depends only on their arguments and which change nothing outside themselves, and immutable data. Code built that way is easy to test and safe to run in parallel, because nothing is shared and changed.

Java added this in Java 8 without adding a function type to the language. Instead, a lambda or method reference is an object that implements a functional interface: an interface with exactly one abstract method. Underneath, javac compiles a lambda body into a private method and emits an invokedynamic instruction; the first time it runs, LambdaMetafactory generates a small hidden class implementing the interface. A lambda that captures nothing can be created once and reused, while a lambda that captures variables becomes a new object holding copies of them. Captured local variables must be effectively final, which is why a lambda cannot increment a counter declared outside it.

The main functional interfaces in java.util.function (all since Java 8)
InterfaceMethodShapeBest for
Function<T, R>applyT to RTransformations; has andThen and compose
UnaryOperator<T>, BinaryOperator<T>applyT to T, (T, T) to TSteps of the same type, reductions
Predicate<T>testT to booleanConditions; has and, or, negate
Supplier<T>getnothing to TLazy or repeated creation
Consumer<T>acceptT to nothingSide effects at the edge of the program
IntUnaryOperator, ToLongFunction and othersvariousPrimitive versionsNumeric code without boxing

Later versions added helpers rather than new concepts: Predicate.not and Optional.isEmpty in Java 11, Stream.toList in Java 16, and sealed interfaces with records in Java 17, which make types such as Either practical. The programs below run on JDK 21.

Lambdas and method references underneath

The program checks what a lambda object is, compares lambdas that capture nothing with lambdas that capture a variable, and uses each of the four kinds of method reference.

Java
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.Supplier;

public class LambdaBasics {

    static Supplier<String> nonCapturing() {
        return () -> "constant";
    }

    static Supplier<String> capturing(String name) {
        return () -> "hello " + name;
    }

    public static void main(String[] args) {
        // A lambda is an object that implements a functional interface
        IntBinaryOperator add = (a, b) -> a + b;
        System.out.println("add.applyAsInt(2, 3) = " + add.applyAsInt(2, 3));
        System.out.println("lambda class is synthetic: " + add.getClass().isSynthetic()
                + ", implements IntBinaryOperator: " + (add instanceof IntBinaryOperator));

        // HotSpot reuses one instance for a lambda that captures nothing
        System.out.println("non-capturing, same object twice: "
                + (nonCapturing() == nonCapturing()));
        System.out.println("capturing, same object twice:     "
                + (capturing("a") == capturing("a")));

        // The four kinds of method reference
        Function<String, Integer> staticRef = Integer::parseInt;           // static method
        String prefix = "id-";
        Function<String, String> boundRef = prefix::concat;               // bound receiver
        BiFunction<String, String, Boolean> unboundRef = String::startsWith; // unbound
        Function<String, StringBuilder> ctorRef = StringBuilder::new;     // constructor
        System.out.println(staticRef.apply("42") + 1);
        System.out.println(boundRef.apply("7"));
        System.out.println(unboundRef.apply("java", "ja"));
        System.out.println(ctorRef.apply("abc").reverse());

        // Captured local variables must be effectively final; collect results instead
        List<String> words = List.of("a", "bb", "ccc");
        int total = words.stream().mapToInt(String::length).sum();
        System.out.println("total length " + total);
    }
}

Output:

Output
add.applyAsInt(2, 3) = 5
lambda class is synthetic: true, implements IntBinaryOperator: true
non-capturing, same object twice: true
capturing, same object twice:     false
43
id-7
true
cba
total length 6
  • The lambda's class is synthetic, generated at run time, and it implements IntBinaryOperator. Calling applyAsInt(2, 3) is an ordinary interface call.
  • The non-capturing lambda returned the same object twice; the capturing one returned a new object each time, because each holds its own copy of name. This is how HotSpot behaves, not a guarantee of the language, so never compare lambdas with ==.
  • The method references printed 43 (static Integer::parseInt plus 1), id-7 (bound to the object prefix), true (unbound: the first argument becomes the receiver of startsWith) and cba (constructor reference, then reverse).
  • The total length 6 was computed with sum() rather than by adding to an outside variable, which a lambda is not allowed to change.

Composing functions

A Function can be combined with another function into a new one. The two methods differ only in order, which is easy to mix up:

  • f.andThen(g) applies f first, then g: g(f(x)).
  • f.compose(g) applies g first, then f: f(g(x)).

The program uses "add 2" and "multiply by 3" with input 5 because the two orders give different answers: (5 + 2) × 3 = 21, but 5 × 3 + 2 = 17. It then builds a URL slug function by folding a list of small string steps together with andThen, and combines predicates.

Java
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

public class Composition {

    public static void main(String[] args) {
        Function<Integer, Integer> plus2 = x -> x + 2;
        Function<Integer, Integer> times3 = x -> x * 3;

        // andThen: this function first, then the argument
        System.out.println("plus2.andThen(times3).apply(5) = " + plus2.andThen(times3).apply(5));
        // compose: the argument first, then this function
        System.out.println("plus2.compose(times3).apply(5) = " + plus2.compose(times3).apply(5));

        // Building a text pipeline from small steps
        List<UnaryOperator<String>> steps = List.of(String::strip, String::toLowerCase,
                s -> s.replaceAll("\\s+", "-"), s -> s.replaceAll("[^a-z0-9-]", ""));
        Function<String, String> slugify = steps.stream()
                .map(op -> (Function<String, String>) op)
                .reduce(Function.identity(), Function::andThen);
        System.out.println("slug: " + slugify.apply("  Hello World, Java 25!  "));

        // Predicates combine with and, or, negate and Predicate.not
        Predicate<String> nonEmpty = Predicate.not(String::isBlank);
        Predicate<String> shortWord = s -> s.length() <= 4;
        Predicate<String> keep = nonEmpty.and(shortWord.negate().or(s -> s.startsWith("j")));
        List<String> words = List.of("java", "", "stream", "map", "lambda", "  ");
        System.out.println("kept: " + words.stream().filter(keep).toList());
    }
}

Output:

Output
plus2.andThen(times3).apply(5) = 21
plus2.compose(times3).apply(5) = 17
slug: hello-world-java-25
kept: [java, stream, lambda]
  • The slug steps run in list order: strip the outer spaces, lowercase, turn each run of spaces into a dash, then drop anything that is not a letter, digit or dash (the comma and the exclamation mark). Adding a step means adding one element to the list.
  • reduce(Function.identity(), Function::andThen) is the general way to chain any number of functions. identity() is the starting point that changes nothing.
  • The predicate keeps non-blank words that are longer than 4 characters or start with "j". "java" is kept by the second rule even though it is short; "map" is short and does not start with "j"; the empty and blank strings fail nonEmpty.

Higher-order functions, currying and memoization

A higher-order function takes a function as an argument or returns one. The program shows three uses:

  • taxAdder(rate) returns a new function with the rate built in, a function factory.
  • curried rewrites a two-argument addition as a function that takes the first argument and returns a function waiting for the second. Supplying only the first argument (partial application) gives add10.
  • memoize takes a function and returns a version that caches results. The inputs repeat 4 and 7 on purpose, so the count of real computations shows the cache working.
Java
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;

public class HigherOrder {

    // Returns a function: a "function factory"
    static Function<Double, Double> taxAdder(double rate) {
        return amount -> Math.round(amount * (1 + rate) * 100) / 100.0;
    }

    // Takes a function and returns a new one that remembers results
    static <T, R> Function<T, R> memoize(Function<T, R> f) {
        Map<T, R> cache = new HashMap<>();
        return x -> {
            R cached = cache.get(x);
            if (cached == null) {
                cached = f.apply(x);
                cache.put(x, cached);
            }
            return cached;
        };
    }

    static int slowCalls = 0;

    static long slowSquare(int n) {
        slowCalls++;
        return (long) n * n;
    }

    public static void main(String[] args) {
        Function<Double, Double> withVat = taxAdder(0.20);
        Function<Double, Double> withGst = taxAdder(0.05);
        System.out.println("100 with 20% VAT: " + withVat.apply(100.0)
                + ", with 5% GST: " + withGst.apply(100.0));

        // Currying: a two-argument function as a chain of one-argument functions
        BiFunction<Integer, Integer, Integer> add = Integer::sum;
        Function<Integer, Function<Integer, Integer>> curried = a -> b -> add.apply(a, b);
        Function<Integer, Integer> add10 = curried.apply(10);       // partial application
        System.out.println("add10(5) = " + add10.apply(5) + ", add10(32) = " + add10.apply(32));

        Function<Integer, Long> fastSquare = memoize(HigherOrder::slowSquare);
        long total = 0;
        for (int n : new int[] {4, 7, 4, 4, 7, 9}) {
            total += fastSquare.apply(n);
        }
        System.out.println("sum of squares: " + total + ", real computations: " + slowCalls);
    }
}

Output:

Output
100 with 20% VAT: 120.0, with 5% GST: 105.0
add10(5) = 15, add10(32) = 42
sum of squares: 227, real computations: 3

The six inputs give 16 + 49 + 16 + 16 + 49 + 81 = 227, but only three distinct values (4, 7 and 9) were computed; the other three came from the cache. This memoize uses a plain HashMap, so it is not thread-safe, and it should only wrap pure functions, whose result depends on nothing but the argument.

Currying is less common in Java than in functional languages because the types become long (Function<Integer, Function<Integer, Integer>>). A factory method like taxAdder usually reads better.

Optional chaining, an Either type and lazy values

Optional lets a sequence of steps stop as soon as one has no value, without null checks. Its limit is that an empty Optional does not say why it is empty. An Either type, built here from a sealed interface and two records, carries either a result (Right) or an error (Left). Its map and flatMap skip all later steps once an error occurs, and the error is kept.

The inputs cover each path:

  • For Optional: a valid port, a blank value that the filter removes, and a missing key.
  • For Either: a valid number, a negative number that fails the second step, and text that fails parsing.

The last part wraps an expensive computation in a Supplier that runs it only on the first get().

Java
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

public class EitherAndLazy {

    // Either: a success value or an error, never both
    sealed interface Either<L, R> permits Left, Right {
        default <T> Either<L, T> map(Function<R, T> f) {
            return switch (this) {
                case Left<L, R> l -> new Left<>(l.error());
                case Right<L, R> r -> new Right<>(f.apply(r.value()));
            };
        }

        default <T> Either<L, T> flatMap(Function<R, Either<L, T>> f) {
            return switch (this) {
                case Left<L, R> l -> new Left<>(l.error());
                case Right<L, R> r -> f.apply(r.value());
            };
        }
    }

    record Left<L, R>(L error) implements Either<L, R> {
    }

    record Right<L, R>(R value) implements Either<L, R> {
    }

    static Either<String, Integer> parse(String s) {
        try {
            return new Right<>(Integer.parseInt(s));
        } catch (NumberFormatException e) {
            return new Left<>("not a number: " + s);
        }
    }

    static Either<String, Integer> positive(int n) {
        return n > 0 ? new Right<>(n) : new Left<>("not positive: " + n);
    }

    // A Supplier that computes its value once, on first use
    static <T> Supplier<T> lazy(Supplier<T> s) {
        return new Supplier<>() {
            private T value;
            private boolean done;

            @Override
            public synchronized T get() {
                if (!done) {
                    value = s.get();
                    done = true;
                }
                return value;
            }
        };
    }

    public static void main(String[] args) {
        // Optional chaining: each step runs only if the previous one produced a value
        Map<String, String> config = Map.of("port", "8080", "host", " ");
        for (String key : List.of("port", "host", "missing")) {
            String port = Optional.ofNullable(config.get(key))
                    .filter(v -> !v.isBlank())
                    .map(Integer::parseInt)
                    .map(p -> "port " + p)
                    .orElse("default used for " + key);
            System.out.println(port);
        }

        // Either keeps the reason for a failure, which Optional cannot
        for (String input : List.of("21", "-4", "abc")) {
            Either<String, Integer> result = parse(input).flatMap(EitherAndLazy::positive)
                    .map(n -> n * 2);
            System.out.println(input + " -> " + result);
        }

        int[] evaluations = {0};
        Supplier<String> report = lazy(() -> {
            evaluations[0]++;
            return "expensive report";
        });
        System.out.println("created supplier, evaluations so far: " + evaluations[0]);
        report.get();
        report.get();
        System.out.println("after two get() calls, evaluations: " + evaluations[0]);
    }
}

Output:

Output
port 8080
default used for host
default used for missing
21 -> Right[value=42]
-4 -> Left[error=not positive: -4]
abc -> Left[error=not a number: abc]
created supplier, evaluations so far: 0
after two get() calls, evaluations: 1
  • The blank host and the missing key both end in the default, and the output does not tell you which problem occurred.
  • With Either, "21" is parsed, checked and doubled to 42. "-4" stops at the positivity check and "abc" at parsing, and each result records its own reason.
  • The lazy supplier did no work when it was created and computed its value exactly once, however many times get() is called. The synchronized keeps it correct if several threads call get() at once.

Design patterns as functions

Several classic object-oriented patterns shrink to a few lines once behaviour can be passed as a value. The program shows a strategy table for a calculator, a decorator that logs every call, and a validation chain where each rule is a function. The second user breaks all three rules so that every error appears.

Java
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.DoubleBinaryOperator;
import java.util.function.Function;
import java.util.function.UnaryOperator;

public class PatternsAsFunctions {

    record User(String name, String email, int age) {
    }

    // Strategy: a map from a key to behaviour replaces an interface and four classes
    static final Map<String, DoubleBinaryOperator> OPS = Map.of(
            "+", (a, b) -> a + b, "-", (a, b) -> a - b,
            "*", (a, b) -> a * b, "/", (a, b) -> a / b);

    // Decorator: wrap a function to add behaviour around every call
    static <T, R> Function<T, R> logged(String name, Function<T, R> f) {
        return x -> {
            R result = f.apply(x);
            System.out.println("  " + name + "(" + x + ") = " + result);
            return result;
        };
    }

    // Validation as a list of rules; each returns an error message or nothing
    static final List<Function<User, Optional<String>>> RULES = List.of(
            u -> u.name().isBlank() ? Optional.of("name is blank") : Optional.empty(),
            u -> u.email().contains("@") ? Optional.empty() : Optional.of("email has no @"),
            u -> u.age() >= 18 ? Optional.empty() : Optional.of("under 18"));

    static List<String> validate(User u) {
        return RULES.stream().map(rule -> rule.apply(u)).flatMap(Optional::stream).toList();
    }

    public static void main(String[] args) {
        for (String op : List.of("+", "-", "*", "/")) {
            System.out.println("7 " + op + " 2 = " + OPS.get(op).applyAsDouble(7, 2));
        }

        UnaryOperator<String> trim = String::strip;
        Function<String, Integer> length = logged("length", String::length);
        System.out.println("decorated call:");
        int n = trim.andThen(length).apply("  hello  ");
        System.out.println("result " + n);

        System.out.println("valid user:   " + validate(new User("Ana", "ana@example.com", 30)));
        System.out.println("invalid user: " + validate(new User(" ", "ben.example.com", 15)));
    }
}

Output:

Output
7 + 2 = 9.0
7 - 2 = 5.0
7 * 2 = 14.0
7 / 2 = 3.5
decorated call:
  length(hello) = 5
result 5
valid user:   []
invalid user: [name is blank, email has no @, under 18]
  • Strategy: the map from "+" to a DoubleBinaryOperator replaces an interface with four implementing classes. 7 / 2 gave 3.5 because the operands are doubles.
  • Decorator: logged returns a function that calls the original and prints the result. The trim step ran first, so the logged input was hello with the spaces already removed.
  • Chain of rules: each rule returns an error or Optional.empty(), and flatMap(Optional::stream) keeps only the errors. The valid user produced an empty list; the invalid one produced all three messages, in rule order. Adding a rule means adding one lambda to the list.

Traps: recursive memoization, eager defaults and shared state

Three mistakes look functional but break at run time. The program shows each with input chosen to trigger it: a recursive Fibonacci, an Optional that has a value, and a parallel stream that adds to an ArrayList.

Java
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.IntStream;

public class FunctionalTraps {

    static final Map<Integer, Long> CACHE = new HashMap<>();

    // Looks elegant, but computeIfAbsent must not modify the map from inside the function
    static long fibBroken(int n) {
        if (n < 2) {
            return n;
        }
        return CACHE.computeIfAbsent(n, k -> fibBroken(k - 1) + fibBroken(k - 2));
    }

    static long fibFixed(int n, Map<Integer, Long> memo) {
        if (n < 2) {
            return n;
        }
        Long known = memo.get(n);
        if (known != null) {
            return known;
        }
        long value = fibFixed(n - 1, memo) + fibFixed(n - 2, memo);
        memo.put(n, value);
        return value;
    }

    static int lookups = 0;

    static String expensiveDefault() {
        lookups++;
        return "computed default";
    }

    public static void main(String[] args) {
        // 1. Recursive computeIfAbsent
        try {
            System.out.println(fibBroken(30));
        } catch (ConcurrentModificationException e) {
            System.out.println("recursive computeIfAbsent: ConcurrentModificationException");
        }
        System.out.println("fib(90) with get/put memo: " + fibFixed(90, new HashMap<>()));

        // 2. orElse always evaluates its argument; orElseGet only when empty
        Optional<String> present = Optional.of("cached");
        present.orElse(expensiveDefault());
        present.orElseGet(FunctionalTraps::expensiveDefault);
        System.out.println("default computed although a value was present: " + lookups + " time");

        // 3. A side effect in a parallel stream: an unsafe list loses or breaks elements
        boolean wentWrong = false;
        for (int run = 0; run < 200 && !wentWrong; run++) {
            List<Integer> unsafe = new ArrayList<>();
            try {
                IntStream.range(0, 100000).parallel().forEach(unsafe::add);
                wentWrong = unsafe.size() != 100000;
            } catch (ArrayIndexOutOfBoundsException e) {
                wentWrong = true;
            }
        }
        List<Integer> safe = IntStream.range(0, 100000).parallel().boxed().toList();
        System.out.println("parallel forEach into ArrayList went wrong within 200 runs: "
                + wentWrong + "; toList() size " + safe.size());
    }
}

Output:

Output
recursive computeIfAbsent: ConcurrentModificationException
fib(90) with get/put memo: 2880067194370816120
default computed although a value was present: 1 time
parallel forEach into ArrayList went wrong within 200 runs: true; toList() size 100000
  • Memoizing a recursive function with HashMap.computeIfAbsent threw ConcurrentModificationException: the function changes the map while computeIfAbsent is changing it, which HashMap detects since Java 9. With a separate get and put, fib(90) was computed with only 89 additions.
  • orElse(expensiveDefault()) computed the default although the Optional held "cached", because Java evaluates method arguments before the call. orElseGet takes a Supplier and calls it only when empty, so the count stayed at 1.
  • Adding to an ArrayList from a parallel forEach lost elements or threw within 200 runs on this 2-core machine. The side effect breaks the "nothing shared and changed" rule. Collecting with toList() gave all 100,000 elements, because each thread builds its own part and the stream merges them.

The cost of boxing

Generic interfaces work on objects, so a Function<Integer, Integer> boxes every argument and result. The program applies the same arithmetic 20 million times through a Function<Integer, Integer> and through an IntUnaryOperator, 3 runs each after a warm-up round. This is a rough comparison on a 2-core Linux machine with JDK 21.

Java
import java.util.function.Function;
import java.util.function.IntUnaryOperator;
import java.util.function.LongSupplier;

public class BoxingCost {

    public static void main(String[] args) {
        // The same function as a generic Function and as a primitive specialization
        Function<Integer, Integer> boxed = x -> x * 3 + 1;
        IntUnaryOperator primitive = x -> x * 3 + 1;
        int n = 20000000;
        for (int round = 0; round < 2; round++) {           // round 0 is warm-up
            boolean print = round == 1;
            time("Function<Integer, Integer>", print, () -> {
                long s = 0;
                for (int i = 0; i < n; i++) {
                    s += boxed.apply(i & 1023);
                }
                return s;
            });
            time("IntUnaryOperator", print, () -> {
                long s = 0;
                for (int i = 0; i < n; i++) {
                    s += primitive.applyAsInt(i & 1023);
                }
                return s;
            });
        }
    }

    static void time(String label, boolean print, LongSupplier work) {
        long best = Long.MAX_VALUE;
        long sum = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            sum = work.getAsLong();
            best = Math.min(best, System.nanoTime() - t0);
        }
        if (print) {
            System.out.printf("%-27s sum %,d  best of 3: %,4d ms%n", label, sum,
                    best / 1000000);
        }
    }
}

Output:

Output
Function<Integer, Integer>  sum 30,709,705,088  best of 3:   12 ms
IntUnaryOperator            sum 30,709,705,088  best of 3:    8 ms

The primitive version was faster, by roughly a third here. The gap is smaller than one might expect because the JIT's escape analysis removed many of the temporary Integer objects in this simple loop; it cannot always do that, for example when boxed values are stored in a collection. For numeric hot paths, use the primitive interfaces and IntStream, LongStream and DoubleStream.

Choosing the right tool

Functional building blocks in java.util.function and java.util
NeedUse
Chain transformationsFunction.andThen, compose, or a stream of map calls
Combine conditionsPredicate.and, or, negate, Predicate.not
Configure behavior once, use it many timesA method that returns a function
A value that may be missingOptional (as a return type, not a field or parameter)
A result or a described failureA sealed Either/Result type, or an exception
Delay work until neededSupplier, with caching if it should run once
Interchangeable algorithmsA Map of keys to functions (strategy)
Behaviour added around callsA method that wraps a function (decorator)
Hot numeric codePrimitive interfaces such as IntUnaryOperator

Pure functions and immutable data make these patterns safe to combine. For immutable data types, see records; for the stream pipeline these functions usually feed, see streams, and for the interfaces themselves, functional interfaces and lambdas.