I found this code that seems to be the non-optimal version of the Sieve of Erastothenes, it gets the N first prime numbers into an array.
private IntPredicate p = x -> true;
private int[] primes(int n) {
return IntStream.iterate(2, i -> i + 1)
.filter(x -> p.test(x))
.peek(i -> p = p.and(k -> k % i != 0))
.limit(n)
.toArray();
}
What's happening internally with the IntPredicate?
This code produces an aggregate Predicate via
IntPredicate.and()method, which would work this way:So every element which successfully passes the
filterresults in a new condition being appended to the current predicate via "logical AND"&&.At the end of the stream execution, the predicate would consist of conditions that check the given number against all the prime number from that would be present in the result.
Note that this hacky implementation is broken:
peek()is an operation which was introduced exclusively to support debugging. It's not meant to be used for performing actions that could affect the result of the execution.peekgives no guaranty regarding the order in which it will be called while executing in parallel, and in certain cases can be optimized away.