Introduction to Java 8 Parallel Stream — Java2Blog

Arpit Mandliya
Apr 23 · 4 min read
package org.arpit.java2blog.java8;import java.util.Arrays;
import java.util.stream.IntStream;
public class Java8ParallelStreamMain { public static void main(String[] args) { System.out.println("=================================");
System.out.println("Using Sequential Stream");
System.out.println("=================================");
int[] array= {1,2,3,4,5,6,7,8,9,10};
IntStream intArrStream=Arrays.stream(array);
intArrStream.forEach(s->
{
System.out.println(s+" "+Thread.currentThread().getName());
}
);
System.out.println("=================================");
System.out.println("Using Parallel Stream");
System.out.println("=================================");
IntStream intParallelStream=Arrays.stream(array).parallel();
intParallelStream.forEach(s->
{
System.out.println(s+" "+Thread.currentThread().getName());
}
);
}
}

Parallel Streams are cool, so should you use it always?

N x Q >10000
package org.arpit.java2blog.java8;
import java.util.ArrayList;
import java.util.List;
public class PerformanceComparisonMain { public static void main(String[] args) {

long currentTime=System.currentTimeMillis();
List<Integer> data=new ArrayList<Integer>();
for (int i = 0; i < 100000; i++) {
data.add(i);
}

long sum=data.stream()
.map(i ->(int)Math.sqrt(i))
.map(number->performComputation(number))
.reduce(0,Integer::sum);

System.out.println(sum);
long endTime=System.currentTimeMillis();
System.out.println("Time taken to complete:"+(endTime-currentTime)/(1000*60)+" minutes");

}

public static int performComputation(int number)
{
int sum=0;
for (int i = 1; i < 1000000; i++) {
int div=(number/i);
sum+=div;

}
return sum;
}
}
long sum=data.stream()
.parallel()
.map(i ->(int)Math.sqrt(i))
.map(number->performComputation(number))
.reduce(0,Integer::sum);

Javarevisited

An humble place to learn Java and Programming better.

Arpit Mandliya

Written by

A java blogger,a geek,a dreamer!! Author of website java2blog.com

Javarevisited

An humble place to learn Java and Programming better.