Java Reference
In-Depth Information
If you want to use the
generate()
method to generate an infinite stream in which the next element is generated
based on the value of the previous element, you will need to use a
Supplier
that stores the last generated element.
Note that a
PrimeUtil
object can act as a
Supplier
whose
next()
instance method remembers the last generated
prime number. The following snippet of code prints five prime numbers after skipping the first 100:
Stream.generate(new PrimeUtil()::next)
.skip(100)
.limit(5)
.forEach(System.out::println);
547
557
563
569
571
Java 8 has added many methods to the
Random
class in the
java.util
package to work with streams. Methods
like
ints()
,
longs()
, and
doubles()
return infinite
IntStream
,
LongStream
, and
DoubleStream
, respectively, which
contain random numbers of the
int
,
long
, and
double
types. The following snippet of code prints five random
int
values from an
IntStream
returned from the
ints()
method of the
Random
class:
// Print five random integers
new Random().ints()
.limit(5)
.forEach(System.out::println);
-1147567659
285663603
-412283607
412487893
-22795557
You may get a different output every time you run the code. You can use the
nextInt()
method of the
Random
class as the
Supplier
in the
generate()
method to achieve the same.
// Print five random integers
Stream.generate(new Random()::nextInt)
.limit(5)
.forEach(System.out::println);
If you want to work with only primitive values, you can use the
generate()
method of the primitive type stream
interfaces. For example, the following snippet of code prints five random integers using the
generate()
static method
of the
IntStream
interface:
IntStream.generate(new Random()::nextInt)
.limit(5)
.forEach(System.out::println);