Code Logo

Sum Numbers Using Stream Reduction

Published at13 Jan 2026
Hard 21 views
Like25

You are given a list of integers and need to return their total sum as a long.

This problem is not asking for filtering or extra transformation. Every number in the input contributes directly to the final result. If the list is empty, the answer should be 0. If the list contains negative values, they should reduce the total in the normal way.

For example, numbers = [1, 2, 3] returns 6, and numbers = [10, 20] returns 30. The test data also shows that values like [-5, -10, -15] should return -30.

So the task is simply to reduce the whole list into one total using Java stream reduction.

Example Input & Output

Example 1
Input
numbers = [10, 20]
Output
30
Explanation

Sum of 10, 20.

Example 2
Input
numbers = []
Output
0
Explanation

Sum of an empty list is 0.

Example 3
Input
numbers = [1, 2, 3]
Output
6
Explanation

Sum of 1, 2, 3.

Algorithm Flow

Recommendation Algorithm Flow for Sum Numbers Using Stream Reduction
Recommendation Algorithm Flow for Sum Numbers Using Stream Reduction

Solution Approach

The Java idea this problem is practicing is stream reduction. A reduction takes many values and combines them into one final result. For summing numbers, that final result is just the running total.

Because the method returns a long, it is a good idea to convert each integer to a long before summing. That keeps the reduction aligned with the return type and avoids relying on an int total first. One clean way is to use a stream that maps each element to long and then sums it.

In Java, a straightforward version is:

return numbers.parallelStream().mapToLong(Integer::longValue).sum();

This matches the method name processParallel and also shows the intended Java feature: a parallel stream with a reduction terminal operation.

You could also write it using reduce, such as reduce(0L, Long::sum) after mapping to long. Both approaches express the same idea: start from zero and keep combining values until one final total remains.

This runs in O(n) time overall because each number is read once. The implementation stays short, but the important concept is that reduction is the right tool when the output is one combined result instead of another collection.

Best Answers

java - Approach 1
import java.util.List;

class Solution {
    public long processParallel(List<Integer> numbers) {
        return numbers.stream()
                     .mapToLong(Integer::longValue)
                     .sum();
    }
}