Supplier
Provides object values.
Acts as a source of values for a Stream
, a source of alternative values for an Optional
, etc.
Method to be implemented is T get()
. Thus, a lambda implementing Supplier
must take no parameters and return/evaluate to a value of the parameterized type T
.
Implemented by a lambda in some cases; however, since state may often need to be maintained across invocations of get()
, Supplier
is sometimes implemented via a class (named or anonymous) with the relevant state fields.
When using Stream
.generate(
Supplier
)
, the size of the resulting stream must generally be controlled through Stream
.limit(long)
or another operation that truncates the stream in some fashion.
Stream
of random numbers using Stream
.generate(
Supplier
)
:Stream.generate(Math::random) // Stream of random values.
.limit(100) // Take only the first 100 values.
.forEach(System.out::println); // Print each value.
This example uses a Supplier
<Double>
, implemented as a lambda (expressed in method reference syntax), to generate a Stream
<Double>
of random values. The stream is truncated after 100 items, and then each item is printed via a Consumer
<Double>
lambda, expressed with method reference syntax.