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 Lambdas and method references underneath Composing functions Higher-order functions, currying and memoization Optional chaining, an Either type and lazy values Design patterns as functions Traps: recursive memoization, eager defaults and shared state The cost of boxing Choosing the right tool
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 invokedynamicLambdaMetafactory
| Interface | Method | Shape | Best for |
|---|---|---|---|
Function<T, R> | apply | T to R | Transformations; has andThencompose |
UnaryOperator<T>BinaryOperator<T> | apply | T to T, (T, T) to T | Steps of the same type, reductions |
Predicate<T> | test | T to boolean | Conditions; has andornegate |
Supplier<T> | get | nothing to T | Lazy or repeated creation |
Consumer<T> | accept | T to nothing | Side effects at the edge of the program |
IntUnaryOperatorToLongFunction | various | Primitive versions | Numeric code without boxing |
Later versions added helpers rather than new concepts: Predicate.notOptional.isEmptyStream.toListEither
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.
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:
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
. CallingIntBinaryOperator is an ordinary interface call.applyAsInt(2, 3) - 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
. This is how HotSpot behaves, not a guarantee of the language, so never compare lambdas withname .== - The method references printed 43 (static
plus 1),Integer::parseInt (bound to the objectid-7 ),prefix (unbound: the first argument becomes the receiver oftrue ) andstartsWith (constructor reference, thencba ).reverse - The total length 6 was computed with
rather than by adding to an outside variable, which a lambda is not allowed to change.sum()
Composing functions
A Function
appliesf.andThen(g) first, thenf :g .g(f(x)) appliesf.compose(g) first, theng :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
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:
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.
is the general way to chain any number of functions.reduce(Function.identity(), Function::andThen) is the starting point that changes nothing.identity()- 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:
returns a new function with the rate built in, a function factory.taxAdder(rate) 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) givescurried .add10 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.memoize
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:
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 memoizeHashMap
Currying is less common in Java than in functional languages because the types become long (Function<Integer, Function<Integer, Integer>>taxAdder
Optional chaining, an Either type and lazy values
OptionalnullOptionalEitherRightLeftmapflatMap
The inputs cover each path:
- For
: a valid port, a blank value that the filter removes, and a missing key.Optional - For
: a valid number, a negative number that fails the second step, and text that fails parsing.Either
The last part wraps an expensive computation in a Supplierget()
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:
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
, "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.Either - The lazy supplier did no work when it was created and computed its value exactly once, however many times
is called. Theget() keeps it correct if several threads callsynchronized at once.get()
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.
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:
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
replaces an interface with four implementing classes. 7 / 2 gave 3.5 because the operands are doubles.DoubleBinaryOperator - Decorator:
returns a function that calls the original and prints the result. The trim step ran first, so the logged input waslogged with the spaces already removed.hello - Chain of rules: each rule returns an error or
, andOptional.empty() 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.flatMap(Optional::stream)
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 OptionalArrayList
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:
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
threwHashMap.computeIfAbsent : the function changes the map whileConcurrentModificationException is changing it, whichcomputeIfAbsent detects since Java 9. With a separateHashMap andget , fib(90) was computed with only 89 additions.put computed the default although theorElse(expensiveDefault()) held "cached", because Java evaluates method arguments before the call.Optional takes aorElseGet and calls it only when empty, so the count stayed at 1.Supplier- Adding to an
from a parallelArrayList lost elements or threw within 200 runs on this 2-core machine. The side effect breaks the "nothing shared and changed" rule. Collecting withforEach gave all 100,000 elements, because each thread builds its own part and the stream merges them.toList()
The cost of boxing
Generic interfaces work on objects, so a Function<Integer, Integer>Function<Integer, Integer>IntUnaryOperator
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:
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 IntegerIntStreamLongStreamDoubleStream
Choosing the right tool
| Need | Use |
|---|---|
| Chain transformations | Function.andThencomposemap |
| Combine conditions | Predicate.andornegatePredicate.not |
| Configure behavior once, use it many times | A method that returns a function |
| A value that may be missing | Optional |
| A result or a described failure | A sealed EitherResult |
| Delay work until needed | Supplier |
| Interchangeable algorithms | A Map |
| Behaviour added around calls | A method that wraps a function (decorator) |
| Hot numeric code | Primitive interfaces such as IntUnaryOperator |
Pure functions and immutable data make these patterns safe to combine. For immutable data types, see