Languages
[Edit]
EN

Java 8 - sum List of Integers with Stream

0 points
Created by:
Maggotta
499

In this article, we would like to show you how to sum List of Integers with Stream in Java 8.

1. Using Stream.reduce()

Edit

In this example, we use Stream.reduce() method where the accumulator function is a lambda expression that adds two Integer values.

Output:

Note:

is equivalent to:

2. Using IntStream sum()

Edit

In this example, to calculate the sum of a list of integers we use:

  • mapToInt() that converts the stream to an IntStream object,
  • sum() method to calculate the sum of the IntStream's elements.

Output:

Note:

In the same way, we can use the mapToLong() and mapToDouble() methods to calculate the sums of longs and doubles.

3. Using Stream.collect()

Edit

In this example, we use collect() method to calculate the sum of a list of integers.

Output:

References

Edit
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join