Java Reference
In-Depth Information
than a specified size. The limit operation is an intermediate operation that produces another stream. You apply the
limit operation using the
limit(long maxSize)
method of the
Stream
interface. The following snippet of code creates
a stream of the first 10 natural numbers:
// Creates a stream of the first 10 natural numbers
Stream<Long> tenNaturalNumbers = Stream.iterate(1L, n -> n + 1)
.limit(10);
You can apply a
forEach
operation on a stream using the
forEach(Consumer<? super T> action)
method of the
Stream
interface. The method returns
void. I
t is a terminal operation. The following snippet of code prints the first
five odd natural numbers on the standard output:
Stream.iterate(1L, n -> n + 2)
.limit(5)
.forEach(System.out::println);
1
3
5
7
9
Let's take a realistic example of creating an infinite stream of prime numbers. Listing 13-3 contains a utility class
called
PrimeUtil
. The class contains two utility methods. The
next()
instance method returns the next prime number
after the last found prime number. The
next(long after)
static method returns the prime number after the specified
number. The
isPrime()
static method checks if a number is a prime number.
Listing 13-3.
A Utility Class to Work with Prime Numbers
// PrimeUtil.java
package com.jdojo.streams;
public class PrimeUtil {
// Used for a stateful PrimeUtil
private long lastPrime = 0L;
// Computes the prime number after the last generated prime
public long next() {
lastPrime = next(lastPrime);
return lastPrime;
}
// Computes the prime number after the specified number
public static long next(long after) {
long counter = after;
// Keep looping until you find the next prime number
while (!isPrime(++counter));
return counter;
}