Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

The Supplier interface

Reference for java.util.function.Supplier: get(), lazy evaluation, factories with constructor references, Stream.generate and orElseGet, plus primitive suppliers.

Supplier<T> is a functional interface for something that produces a value without taking any input. Its single method is T get(). Think of it as a "value on demand": a factory, a lazy computation, a source of defaults.

Suppliers are used wherever the value is expensive or only sometimes needed. Optional.orElseGet(), Stream.generate(), Objects.requireNonNull(obj, supplier), Map.computeIfAbsent() (via a function), ThreadLocal.withInitial() and CompletableFuture.supplyAsync() all take a Supplier.

Java
Supplier<List<String>> factory = ArrayList::new;
List<String> a = factory.get();
List<String> b = factory.get();   // a different list each time

Try it

Java Lazy defaults and factories

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Generating streams and caching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
@FunctionalInterface
public interface Supplier<T> {
    T get();
}
Member Description
get() Produces and returns a result. May return a new or a shared object, and may return null unless the caller forbids it.

There are no default methods. Primitive versions: IntSupplier.getAsInt(), LongSupplier.getAsLong(), DoubleSupplier.getAsDouble(), BooleanSupplier.getAsBoolean().

Usage notes

  • No guarantee of a new object. The contract does not say whether each get() returns a fresh instance; () -> CONSTANT returns the same one every time.
  • orElse vs. orElseGet: orElse(x) evaluates x even when the Optional has a value. Pass a supplier to orElseGet when building the default is costly or has side effects.
  • Constructor references: ArrayList::new, StringBuilder::new and Person::new (no-argument constructor) all fit Supplier.
  • Not thread-safe by itself. A supplier that caches a value (like Lazy above) needs synchronization or a holder idiom if several threads call it.
  • Checked exceptions cannot be thrown from get(). Callable is the equivalent that may throw.
  • Infinite streams: Stream.generate() never ends; always add limit() or a short-circuiting terminal operation.
  • Randomness: a Supplier over a Random with a fixed seed is a convenient deterministic generator for tests.