A decorator lambda takes an existing Function and returns a new one that runs extra behavior, such as logging, before and after delegating to the original, without changing the original function's code.
static Function<Integer, Integer> withLogging(Function<Integer, Integer> original) {
return x -> {
System.out.println("Calling with input " + x);
int result = original.apply(x);
System.out.println("Result was " + result);
return result;
};
}
Function<Integer, Integer> square = x -> x * x;
Function<Integer, Integer> logged = withLogging(square);
logged.apply(4);
Calling with input 4
Result was 16
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