Wrapping a computation in a Supplier means the code only runs when get() is actually called, which is why the supplier below can be created without doing any work at all.
int[] calls = {0};
Supplier<Integer> lazyTotal = () -> {
calls[0]++;
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
return sum;
};
System.out.println("Supplier created, calls so far: " + calls[0]);
System.out.println("First get(): " + lazyTotal.get());
System.out.println("Calls after use: " + calls[0]);
Supplier created, calls so far: 0
First get(): 15
Calls after use: 1
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