A higher-order function treats behavior as data: it takes a Function as a parameter and produces a new Function built from it, here wrapping a calculation so it never returns a negative result.
static Function<Integer, Integer> nonNegative(Function<Integer, Integer> f) {
return x -> Math.max(0, f.apply(x));
}
Function<Integer, Integer> subtractTen = x -> x - 10;
Function<Integer, Integer> safeSubtract = nonNegative(subtractTen);
System.out.println("safeSubtract(3): " + safeSubtract.apply(3));
System.out.println("safeSubtract(15): " + safeSubtract.apply(15));
safeSubtract(3): 0
safeSubtract(15): 5
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27