Lambda: a lazy Supplier defers an expensive computation until first use

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.

Code
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]);
Output
Supplier created, calls so far: 0
First get(): 15
Calls after use: 1
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