Parallel Stream Examples
The Stream API allows running in parallel in multiple CPU cores to speed up processing when the algorithm requires a very large number of loops. Below are some examples that I created as mnemonic and experimental usage.
Note that list.stream().parallel() can also be written as list.parallelStream().
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
13 15 14 18 7 12 17 11 6 9 10 8 19 1 5 4 3 16 20 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
210
210
20
1
10.5
10.5
Note that list.stream().parallel() can also be written as list.parallelStream().
Function<Integer, List<Integer>> getList = (n) -> { return Stream.iterate(1, i -> i + 1) .limit(n) .collect(Collectors.toList()); }; List<Integer> dataList = getList.apply(20); // Run in sequence to print dataList.forEach(x -> System.out.print (x + " ")); System.out.println(); // Run in parallel to print dataList.stream() .parallel() .forEach(x -> System.out.print(x + " ")); System.out.println(); // Run in paraellel to map, collect, and print dataList.stream() .parallel() .map(x -> x + " ") .collect(Collectors.toList()) .forEach(System.out::print); System.out.println(); int iResult; // Run in sequence to sum iResult = dataList.stream() .reduce(0, Integer::sum); System.out.println(iResult); // Run in parallel to sum iResult = dataList.stream() .parallel() .reduce(0, Integer::sum); System.out.println(iResult); // Run in paraellel to find the max iResult = dataList.stream() .parallel() .reduce(Integer::max) .get(); System.out.println(iResult); // Run in paraellel to find the min iResult = dataList.stream() .parallel() .reduce(Integer::min) .get(); System.out.println(iResult); double dResult; // Run parallel() then mapToDouble(ToDoubleFunction<? super T> mapper), and calculate the average dResult = dataList.stream() .parallel() .mapToDouble(x -> x) .average() .getAsDouble(); System.out.println(dResult); // Run mapToDouble(ToDoubleFunction<? super T> mapper) then parallel(), and calculate the average dResult = dataList.stream() .mapToDouble(x -> x) .parallel() .average() .getAsDouble(); System.out.println(dResult);
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
13 15 14 18 7 12 17 11 6 9 10 8 19 1 5 4 3 16 20 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
210
210
20
1
10.5
10.5
Comments
Post a Comment