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.
Supplier<List<String>> factory = ArrayList::new; List<String> a = factory.get(); List<String> b = factory.get(); // a different list each time
Try it
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.
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
@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;() -> CONSTANTreturns the same one every time. orElsevs.orElseGet:orElse(x)evaluatesxeven when the Optional has a value. Pass a supplier toorElseGetwhen building the default is costly or has side effects.- Constructor references:
ArrayList::new,StringBuilder::newandPerson::new(no-argument constructor) all fitSupplier. - Not thread-safe by itself. A supplier that caches a value (like
Lazyabove) needs synchronization or a holder idiom if several threads call it. - Checked exceptions cannot be thrown from
get().Callableis the equivalent that may throw. - Infinite streams:
Stream.generate()never ends; always addlimit()or a short-circuiting terminal operation. - Randomness: a
Supplierover aRandomwith a fixed seed is a convenient deterministic generator for tests.