Java Reference
In-Depth Information
2
3
5
7
11
Sometimes you may want to discard some elements of a stream. This is accomplished using the skip operation.
The
skip(long n)
method of the
Stream
interface discards (or skips) the first
n
elements of the stream. This is an
intermediate operation. The following snippet of code uses this operation to print five prime numbers, skipping the
first 100 prime numbers:
Stream.iterate(2L, PrimeUtil::next)
.skip(100)
.limit(5)
.forEach(System.out::println);
547
557
563
569
571
Using everything you have learned about streams, can you write a stream pipeline to print five prime numbers
that are greater than 3000? This is left as an exercise for the readers.
Using the generate( ) Method
The
generate(Supplier<T> s)
method uses the specified
Supplier
to generate an infinite sequential unordered
stream. The following snippet of code prints five random numbers greater than or equal to 0.0 and less than 1.0 using
the
random()
static method of the
Math
class. You may get a different output.
Stream.generate(Math::random)
.limit(5)
.forEach(System.out::println);
0.05958352209327644
0.8122226657626394
0.5073323815997652
0.9327951597282766
0.4314430923877808