Lambda: a decorator wraps a Function to add logging around its logic

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.

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);
Output
Calling with input 4
Result was 16
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms