I am experimenting with Java's Streams and trying to figure out what is possible as well as their strengths and weaknesses. Currently I am trying to implement the Sieve of Eratosthenes using a stream, but cannot seem to find a good way to loop through previously filtered values without storing them in a separate collection.
I am wanting to accomplish something like this:
IntStream myStream = IntStream.range(0,3);
myStream.filter(s -> {
System.out.print("[filtering "+s+"] ");
myStream.forEach(q -> System.out.print(q+", "));
System.out.println();
return true; //eventually respond to values observed on the line above
});
With a desired output of:
[filtering 0]
[filtering 1] 0,
[filtering 2] 0, 1,
[filtering 3] 0, 1, 2,
Note that while filtering each new value all previously filtered values are observed. This would allow an easy implementation of the Sieve of Eratosthenes because I could filter out all non-prime values and for each new value check for divisibility against all numbers that have previously passed the prime filter.
However, the above example gives me an error in NetBeans:
local variables referenced from a lambda expression must be final or effectively final
This appears to be because I am referencing myStream within a filter that is already acting on myStream. Is there any good way of working around this error (ie. making a final copy of the stream containing only the values that have been filtered so far), or is there a better approach to this sort of problem without using a separate collection to store values?
final
keyword beforeIntStream myStream
. But the code would not be correct anyway, because you need to change the second line tomyStream = myStream.filter(...)
, otherwise you would be using the stream without filtering.