Sobes.tech
Senior

Sum 200 numbers. Should you use a regular or parallel stream?

sobes.tech AI

Answer from AI

For adding 200 numbers, using a regular (sequential) stream is preferable over a parallel one.

Reasons:

  • Parallel streams are effective with large data volumes and complex operations, where the overhead of creating and managing threads is justified.
  • For a small collection (200 elements), the overhead of parallelization may outweigh the benefits.
  • Addition is a simple operation that is quickly performed sequentially.

Example:

int sum = numbers.stream().mapToInt(Integer::intValue).sum();

Using .parallelStream() for such a task will not provide a noticeable advantage and may even slow down execution.