0Pricing
Java Academy · Lesson

Supplier and Consumer

Produce and consume values.

What Supplier Does

Supplier<T> takes no arguments and produces a value of type T.

  • Its method is T get().
  • Perfect for lazy or deferred value creation.
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        Supplier<String> greeting = () -> "Hello!";
        System.out.println(greeting.get());
    }
}

Suppliers Are Lazy

The code inside a Supplier runs only when get is called. This makes suppliers ideal for expensive defaults you may never need.

import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        Supplier<Integer> expensive = () -> {
            System.out.println("computing...");
            return 42;
        };
        System.out.println("before get");
        System.out.println(expensive.get());
    }
}

All lessons in this course

  1. Function and BiFunction
  2. Supplier and Consumer
  3. Predicate and Composition
  4. Custom Functional Interfaces
← Back to Java Academy