Lambda: memoizing a Function caches results in a backing Map

A memoizing wrapper checks a Map for a previously computed result before calling the real function, trading memory for speed whenever the same input is requested more than once.

Code
Map<Integer, Integer> cache = new HashMap<>();
int[] calls = {0};
Function<Integer, Integer> slowSquare = x -> {
    calls[0]++;
    return x * x;
};
Function<Integer, Integer> memoized = x -> cache.computeIfAbsent(x, slowSquare::apply);
System.out.println("memoized(6): " + memoized.apply(6));
System.out.println("memoized(6) again: " + memoized.apply(6));
System.out.println("memoized(7): " + memoized.apply(7));
System.out.println("Real calls made: " + calls[0]);
Output
memoized(6): 36
memoized(6) again: 36
memoized(7): 49
Real calls made: 2
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