Java parallelStream not showing correct result
This question already has an answer here:
I think your code having issue with count()
method. As parallelStream
will try to perform task concurrently. This method should be synchronized
or you can make totaleven
as Atomtic Integer. Hope it helps.
Instead of using the forEach to increment a counter you can use the terminal operation Stream:count
For example
totaleven = randomList.stream().filter(e -> e % 2 ==0).count();
totaleven = 0;
totaleven = randomList.parallelStream().filter(e -> e % 2 ==0).count();
totaleven would need to be changed to data type long or casting applied.
What's wrong with parallel stream result? If it is too small then most likely you have problem with totaleven++
as it is not thread safe. Use AtomicInteger or any other thread safe solution.