Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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 1

Notes

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

In the tutorial

  • Functional interfaces — Functional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.

Thanks for reading!

Donate to the site — we work hard for you.