Skip to content

Instantly share code, notes, and snippets.

@ojitha
Last active November 23, 2019 06:27
Show Gist options
  • Select an option

  • Save ojitha/f24b5b5e178e3f9e2ae043dc4752f559 to your computer and use it in GitHub Desktop.

Select an option

Save ojitha/f24b5b5e178e3f9e2ae043dc4752f559 to your computer and use it in GitHub Desktop.
This java example shows how to use the parallel stream to do the reduce function.
import java.math.BigInteger;
import java.util.Arrays;
import java.util.stream.IntStream;
//var r =IntStream.rangeClosed(1,5)
// .reduce(1,(x,y) -> x * y);
// //.forEach(System.out::println);
static BigInteger factorial(int n){
return IntStream.rangeClosed(1, n)
.mapToObj(BigInteger::valueOf)
.parallel() //use of the parallel
.reduce(BigInteger.ONE, BigInteger::multiply);
}
Long[] times = new Long[10];
for(int i = 0; i < 10; i++){
long time = System.nanoTime();
factorial(100000);
times[i]=(System.nanoTime() - time)/1000000;
}
times
Arrays.stream(times).reduce((x, y)->x+y).get()/times.length;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment