Java Reference
In-Depth Information
Step 2: Take the head
An IntStream comes with the method findFirst, which can be used to return the first element:
static int head(IntStream numbers){
return numbers.findFirst().getAsInt();
}
Step 3: Filter the tail
Define a method to get the tail of a stream:
static IntStream tail(IntStream numbers){
return numbers.skip(1);
}
Given the head of the stream, you can filter the numbers as follows:
IntStream numbers = numbers();
int head = head(numbers);
IntStream filtered = tail(numbers).filter(n -> n % head != 0);
Step 4: Recursively create a stream of primes
Here comes the tricky part. You might be tempted to try passing back the resulting filtered
stream so you can take its head and filter more numbers, like this:
static IntStream primes(IntStream numbers) {
int head = head(numbers);
return IntStream.concat(
IntStream.of(head),
primes(tail(numbers).filter(n -> n % head != 0))
);
}
Bad news
Unfortunately, if you run the code in step 4, you'll get the following error:
“java.lang.IllegalStateException: stream has already been operated upon or closed.” Indeed,
 
Search WWH ::




Custom Search