I recently learned about Stream
s in Java 8 and saw this example:
IntStream stream = IntStream.range(1, 20);
Now, let's say that we want to find the first number that's divisable both by 3 and a 5. We'd probably filter
twice and findFirst
as follows:
OptionalInt result = stream.filter(x -> x % 3 == 0)
.filter(x -> x % 5 == 0)
.findFirst();
That's all sounds pretty reasonable. The surprising part came when I tried to do this:
OptionalInt result = stream.filter(x -> {System.out.println(x); return x % 3 == 0;})
.filter(x -> {System.out.println(x); return x % 5 == 0;})
.findFirst();
System.out.println(result.getAsInt());
I expected to get something like: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
and then: 3 6 9 12 15 18
. Because we first iterate over all the the numbers between 1 to 20, filter out only those that are divisable by 3 and then iterate this new Stream
and find those that are divisable by 5.
But instead I got this output: 1 2 3 3 4 5 6 6 7 8 9 9 10 11 12 12 13 14 15 15 15
It looks like it doesn't go over all the numbers. Moreover, it looks like it checks x % 5 == 0
only for those numbers that are divisable by 3.
I don't understand how come it doesn't iterate over all of the numbers.
Here's an online snippet of the code: http://www.tryjava8.com/app/snippets/5454a7f2e4b070922a64002b