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