Skip to lesson

Consumer and Supplier

Some tasks only act on a value, like printing a receipt. Others only produce one, like a new order ID. Each needs its own shape of lambda.

Consumer<T>: do something with each value

A Consumer<T> takes a value and returns nothing (accept); a Supplier<T> takes nothing and returns a value (get).

Some code does not compute an answer. It prints a line, writes a log entry, adds to a list or sends an SMS. A change like this, visible outside the lambda, is called a side effect. Consumer<T> is the shape for it: void accept(T t).

Example 1 · Consumer: one loop, many actions

ConsumerDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;
public class ConsumerDemo {    static void forEachName(List<String> names, Consumer<String> action) {        for (String n : names) {            action.accept(n);        }    }
    public static void main(String[] args) {        List<String> present = List.of("Rohan", "Kavya", "Divya");
        Consumer<String> printLine = name -> System.out.println("Present: " + name);        forEachName(present, printLine);
        List<String> log = new ArrayList<>();        forEachName(present, name -> log.add("marked " + name));        System.out.println("Log: " + log);
        present.forEach(name -> System.out.println("SMS to parent of " + name));    }}
Output
Present: Rohan
Present: Kavya
Present: Divya
Log: [marked Rohan, marked Kavya, marked Divya]
SMS to parent of Rohan
SMS to parent of Kavya
SMS to parent of Divya

What this code does

  • forEachName owns the loop and calls action.accept(n) for each name. The first call prints, the second adds to a log list, and neither changes the method.
  • list.forEach does the same job and is built into every list. It also takes a Consumer.

Without it, every "do this to each item" needs its own loop: one loop to print the attendance sheet, one to log it, one to send reminders. With a Consumer, one method or list.forEach(action) owns the loop, and the caller passes only the action. A consumer often uses something from outside, such as System.out or a log list. Calling methods on an outside object, like log.add(...), is fine.

Supplier<T>: make a value when asked

Supplier<T> has one method, T get(), with no input. It is a value maker: every call to get runs the lambda and returns what it produces.

Example 2 · Supplier: default values and an ID generator

SupplierDemo.javaJava
import java.util.function.Supplier;
public class SupplierDemo {    static int lastId = 1000;   // a field, so the lambda may change it
    public static void main(String[] args) {        Supplier<String> defaultCity = () -> "Bengaluru";        System.out.println("City: " + defaultCity.get());
        Supplier<String> nextAdmissionNo = () -> {            lastId++;            return "ADM" + lastId;        };        System.out.println(nextAdmissionNo.get());        System.out.println(nextAdmissionNo.get());        System.out.println(nextAdmissionNo.get());    }}
Output
City: Bengaluru
ADM1001
ADM1002
ADM1003

What this code does

  • A Supplier takes nothing, so its lambda starts with (). Every get() runs the body again.
  • nextAdmissionNo changes the field lastId, so each call returns the next number. The counter is a field on purpose: a lambda cannot change a local variable.

Typical uses are a default value (() -> "Guest"), a fresh object (() -> new ArrayList<>()), the next ID from a counter, or a random OTP. A counter that must change between calls lives in a field of a class, not in a local variable; the "Effectively final variables in lambdas" lesson explains why. A supplier that uses Random gives different values on every run. The examples here create the random maker with a fixed seed, new Random(7), so the numbers are the same each time and you can check the output.

Lazy work: the value is made only when get is called

Java works out every argument before a method starts, so in valueOrDefault(name, loadDefaultName()) the default is built even when unused. Pass a Supplier<String>, () -> loadDefaultName(), and the method calls fallback.get() only when needed: that is lazy; doing it up front is eager.

Example 3 · Lazy default: the work runs only when needed

LazyDefaultDemo.javaJava
import java.util.function.Supplier;
public class LazyDefaultDemo {    static String loadDefaultName() {        System.out.println("  (reading the default from the settings file...)");        return "Guest";    }
    static String eagerOrDefault(String name, String fallback) {        return name != null ? name : fallback;    }
    static String lazyOrDefault(String name, Supplier<String> fallback) {        return name != null ? name : fallback.get();    }
    public static void main(String[] args) {        System.out.println("Eager, name given:");        System.out.println(eagerOrDefault("Riya", loadDefaultName()));
        System.out.println("Lazy, name given:");        System.out.println(lazyOrDefault("Riya", () -> loadDefaultName()));
        System.out.println("Lazy, name missing:");        System.out.println(lazyOrDefault(null, () -> loadDefaultName()));    }}
Output
Eager, name given:
  (reading the default from the settings file...)
Riya
Lazy, name given:
Riya
Lazy, name missing:
  (reading the default from the settings file...)
Guest

What this code does

  • In the eager call, Java runs loadDefaultName() before eagerOrDefault even starts, so the file is read although "Riya" is used.
  • In the lazy calls, the method receives a recipe. It calls fallback.get() only when the name is null, so the file is read just once, in the last call.

If that call reads a file or asks a server, the work is wasted.

Java itself uses this idea. Objects.requireNonNullElseGet(value, supplier) builds the default only for null, and logging libraries accept a Supplier<String> so that a long debug message is built only when debug logging is on.

Trap: a Supplier runs again on every get call

A Supplier does not store a value. It stores the recipe for a value. Every get() cooks it again.

Example 4 · Trap: every get() makes a new value

SupplierTrapDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.function.Supplier;
public class SupplierTrapDemo {    public static void main(String[] args) {        Random random = new Random(7);   // fixed seed, so the output is the same on every run        Supplier<Integer> otp = () -> 100000 + random.nextInt(900000);
        System.out.println("SMS sent with OTP " + otp.get());        System.out.println("Server expects OTP " + otp.get());
        Supplier<List<String>> cart = () -> new ArrayList<>();        cart.get().add("Notebook");        System.out.println("Cart: " + cart.get());    }}
Output
SMS sent with OTP 564236
Server expects OTP 649164
Cart: []

What this code does

  • The OTP supplier runs its lambda on each get(), so the SMS and the server check use two different numbers.
  • cart.get() makes a new empty list every time. "Notebook" goes into the first list, which is then lost, and the second get() returns a different, empty list.

Example 5 · Fix: call get() once and keep the value

SupplierFixDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.function.Supplier;
public class SupplierFixDemo {    public static void main(String[] args) {        Random random = new Random(7);        Supplier<Integer> otp = () -> 100000 + random.nextInt(900000);
        int code = otp.get();   // make the OTP once        System.out.println("SMS sent with OTP " + code);        System.out.println("Server expects OTP " + code);
        Supplier<List<String>> newCart = () -> new ArrayList<>();        List<String> cart = newCart.get();   // make the list once        cart.add("Notebook");        cart.add("Pen");        System.out.println("Cart: " + cart);    }}
Output
SMS sent with OTP 564236
Server expects OTP 564236
Cart: [Notebook, Pen]

What this code does

  • The OTP is made once and stored in code, so the SMS and the check agree.
  • The cart list is made once and kept in a variable. The supplier is still useful as a recipe: each new customer could call newCart.get() for their own empty cart.

With an OTP supplier, sms(otp.get()) and then check(otp.get()) use two different OTPs, so the user can never log in. With () -> new ArrayList<>(), cart.get().add("Pen") adds to one new list, and the next cart.get() returns a different, empty list. The fix is simple: when you need the same value twice, call get() once and keep the result in a variable.

Find the bug

Find the repeated get()

Tap the line that breaks the idea, then check the fix.

The OTP that is checked must be the one that was sent.

Round 1 of 2
Rule of thumb: a Supplier is for "make one when I ask". If you want "the same value every time", store the value, not the supplier.

Next step

Check your understanding

11 quick questions