Supplier
A supplier: a no-argument function that returns a value.
Available since: Java 8
Syntax
@FunctionalInterface
public interface Supplier<T> {
T get();
}Examples
Deferred creation of a value:
void main() {
Supplier<List<String>> newList = ArrayList::new;
List<String> a = newList.get();
a.add("x");
IO.println(a + " " + newList.get());
Supplier<String> greeting = () -> "Hello at step " + a.size();
IO.println(greeting.get());
}Output:
[x] []
Hello at step 1Notes
The value is created only when get() is called — this is used by orElseGet(), Stream.generate(), CompletableFuture.supplyAsync() and computeIfAbsent(). Every get() call runs the function again.
See also
- Consumer — An action that takes a value and returns nothing.
- Optional.orElseGet() — Returns the value, or calls a function to create a fallback.
- Stream.generate() — Creates an infinite stream from the values of a supplier function.
- CompletableFuture.supplyAsync() — Runs a computation asynchronously and returns a `CompletableFuture`.
In the tutorial
- Functional interfaces — Functional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.