Summing elements in a stream of integers is done by converting to an IntStream with mapToInt, then calling its sum() terminal operation.
Key Points: • mapToInt(Integer::intValue) converts a Stream<Integer> into a primitive IntStream, avoiding boxing overhead during the sum. • IntStream provides sum(), average(), min(), max(), and summaryStatistics() directly as terminal operations. • For a Stream<Integer>, calling reduce(0, Integer::sum) is an alternative that avoids the intermediate IntStream conversion. • Using the primitive stream is generally more efficient for numeric aggregation than boxed Integer streams. • sum() returns 0 for an empty stream, since 0 is the identity value for addition.
Example: Given the list [1, 2, 3, 4, 5], converting to an IntStream and calling sum() produces 15.
Code Example:
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();Interview Tip: A concise interview answer is:
"I convert the boxed stream to a primitive IntStream with mapToInt(Integer::intValue), then call sum(), which avoids the boxing overhead of using reduce(0, Integer::sum) directly on a Stream<Integer> and gives access to other numeric aggregates like average() and max()."