|
| 1 | +package com.learn.parallelstream; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | +import java.util.stream.Collectors; |
| 5 | +import java.util.stream.IntStream; |
| 6 | + |
| 7 | +/** |
| 8 | + * <p> |
| 9 | + * It is always recommended to check the performance before |
| 10 | + * going to the assumption that parallel stream is going to perform better. |
| 11 | + * </p> |
| 12 | + */ |
| 13 | +public class ParallelStreamBoxedExample { |
| 14 | + |
| 15 | + public static void main(String[] args) { |
| 16 | + |
| 17 | + /** |
| 18 | + * This are not primitive integers. |
| 19 | + * These are Wrapper integer Objects. |
| 20 | + */ |
| 21 | + List<Integer> integerList = IntStream.rangeClosed(1, 10000).boxed().collect(Collectors.toList()); |
| 22 | + sequentialSum(integerList); |
| 23 | + parallelSum(integerList); |
| 24 | + } |
| 25 | + |
| 26 | + |
| 27 | + /** |
| 28 | + * <p> |
| 29 | + * Performing the Sequential Stream on the input. |
| 30 | + * </p> |
| 31 | + */ |
| 32 | + public static int sequentialSum(List<Integer> integerList) { |
| 33 | + long startTime = System.currentTimeMillis(); |
| 34 | + int sum = integerList |
| 35 | + .stream() |
| 36 | + .reduce(0, Integer::sum); |
| 37 | + long endTime = System.currentTimeMillis(); |
| 38 | + System.out.println("Sequential Stream Time Take : " + (endTime - startTime)); |
| 39 | + return sum; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * <p> |
| 44 | + * Performing the parallel Stream on the input. |
| 45 | + * here, it need to convert unboxing from Integer to int for each and every value. |
| 46 | + * </p> |
| 47 | + */ |
| 48 | + public static int parallelSum(List<Integer> integerList) { |
| 49 | + long startTime = System.currentTimeMillis(); |
| 50 | + int sum = integerList |
| 51 | + .parallelStream() |
| 52 | + .reduce(0, Integer::sum); // here effort is required to perform Unboxing. |
| 53 | + long endTime = System.currentTimeMillis(); |
| 54 | + System.out.println("Parallel Stream Time Taken : " + (endTime - startTime)); |
| 55 | + return sum; |
| 56 | + } |
| 57 | +} |
0 commit comments