|
1 | 1 | package org.baeldung.java.streams; |
2 | 2 |
|
3 | | -import static org.junit.Assert.assertEquals; |
4 | | -import static org.junit.Assert.assertTrue; |
| 3 | +import org.junit.Test; |
5 | 4 |
|
6 | 5 | import java.util.ArrayList; |
7 | 6 | import java.util.List; |
8 | 7 | import java.util.concurrent.ExecutionException; |
9 | 8 | import java.util.concurrent.ForkJoinPool; |
| 9 | +import java.util.stream.Collectors; |
| 10 | +import java.util.stream.LongStream; |
10 | 11 | import java.util.stream.Stream; |
11 | 12 |
|
12 | | -import org.junit.Test; |
| 13 | +import static org.junit.Assert.assertEquals; |
| 14 | +import static org.junit.Assert.assertTrue; |
13 | 15 |
|
14 | 16 | public class ThreadPoolInParallelStream { |
15 | 17 |
|
16 | 18 | @Test |
17 | 19 | public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() |
18 | 20 | throws InterruptedException, ExecutionException { |
19 | | - List<Long> aList = new ArrayList<>(); |
20 | | - long lastNum = 1_000_000; |
21 | 21 | long firstNum = 1; |
22 | | - |
23 | | - long expectedTotal = (lastNum + firstNum) * lastNum / 2; |
24 | | - |
25 | | - for(long i = firstNum; i <= lastNum; i++){ |
26 | | - aList.add(i); |
27 | | - } |
28 | | - |
| 22 | + long lastNum = 1_000_000; |
| 23 | + |
| 24 | + List<Long> aList = LongStream.range(firstNum, lastNum).boxed() |
| 25 | + .collect(Collectors.toList()); |
| 26 | + |
29 | 27 | ForkJoinPool customThreadPool = new ForkJoinPool(4); |
30 | | - long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce( |
31 | | - 0L, (x, y) -> { |
32 | | - return x + y; |
33 | | - })).get(); |
| 28 | + long actualTotal = customThreadPool.submit(() -> aList.parallelStream() |
| 29 | + .reduce(0L, Long::sum)).get(); |
34 | 30 |
|
35 | | - assertEquals(expectedTotal, actualTotal); |
| 31 | + assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); |
36 | 32 | } |
37 | 33 |
|
38 | 34 | @Test |
|
0 commit comments