title: Java 8 Parallel processing and Lambda expression
body: <p>I want to test how much faster Java8 parallel stream so I wrote a program .The program count the number of prime numbers in a given list of numbers. The program counts prime numbers in there ways:</p>
  
  <ol>
  <li>using for loop;</li>
  <li>by using lambda expression;</li>
  <li>by using lambda expression(parallel stream).</li>
  </ol>
  
  <p>Before executing the program I was expecting that parallel stream version should be faster. But the result is </p>
  
  <p>Total prime no found 664579 in 4237 mili sec ----for loop version<br/>
  Total prime no found 664579 in 2440 mili sec ----parallel stream<br/>
  Total prime no found 664579 in 2166 mili sec ----lambda expression<br/></p>
  
  <p><strong>My doubt is why parallel version is slower then lambda version</strong></p>
  
  <pre><code>List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();
          for (int i = 0; i &lt; 10000000; i++) {
              numbers.add(i);
          }
          Stopwatch stopwatch = Stopwatch.createStarted();
          int counter = 0;
          for (int number : numbers) {
              if (isPrime(number)) {
                  counter++;
              }
          }
          stopwatch.stop();
          System.out.println("Total prime no found " + counter + " in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " mili sec");
  
          stopwatch = Stopwatch.createStarted();
          long count1 = numbers.parallelStream().filter(n -&gt; isPrime(n)).count();
          stopwatch.stop();
          System.out.println("Total prime no found " + count1 + " in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " mili sec");
  
          stopwatch = Stopwatch.createStarted();
          long count2 = numbers.stream().filter(n -&gt; isPrime(n)).count();
          System.out.println("Total prime no found " + count2 + " in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " mili sec");
          stopwatch.stop();
  </code></pre>
  
  <p><strong>The above program uses google Guava library to calculate time elapsed.</strong></p>