Skip to content

Commit a312ce5

Browse files
committed
Refactor ThreadPoolInParallelStream
1 parent 1a10cae commit a312ce5

1 file changed

Lines changed: 13 additions & 17 deletions

File tree

‎core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStream.java‎

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,34 @@
11
package org.baeldung.java.streams;
22

3-
import static org.junit.Assert.assertEquals;
4-
import static org.junit.Assert.assertTrue;
3+
import org.junit.Test;
54

65
import java.util.ArrayList;
76
import java.util.List;
87
import java.util.concurrent.ExecutionException;
98
import java.util.concurrent.ForkJoinPool;
9+
import java.util.stream.Collectors;
10+
import java.util.stream.LongStream;
1011
import java.util.stream.Stream;
1112

12-
import org.junit.Test;
13+
import static org.junit.Assert.assertEquals;
14+
import static org.junit.Assert.assertTrue;
1315

1416
public class ThreadPoolInParallelStream {
1517

1618
@Test
1719
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()
1820
throws InterruptedException, ExecutionException {
19-
List<Long> aList = new ArrayList<>();
20-
long lastNum = 1_000_000;
2121
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+
2927
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();
3430

35-
assertEquals(expectedTotal, actualTotal);
31+
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
3632
}
3733

3834
@Test

0 commit comments

Comments
 (0)