1. Overview

We usually use the Java Stream API for processing collections of data.

One nice feature is support for operations on numeric streams, like the sum operation. However, we cannot process all numeric types in this way.

In this tutorial, we’ll see how to perform the sum operation on streams of numbers like BigDecimal.

2. How We Usually Sum a Stream

The Stream API provides streams of numbers, including IntStream, DoubleStream, and LongStream.

Let’s remind ourselves how these work by creating a numeric stream. Then, we’ll calculate its total with IntStream#sum:

IntStream intNumbers = IntStream.range(0, 3);
assertEquals(3, intNumbers.sum());

We can do a similar thing starting with a list of Doubles. By using streams, we can convert from an object stream to a DoubleStream using mapToDouble:

List<Double> doubleNumbers = Arrays.asList(23.48, 52.26, 13.5);
double result = doubleNumbers.stream()
    .mapToDouble(Double::doubleValue)
    .sum();
assertEquals(89.24, result, .1);

So, it would be useful if we could sum up a collection of BigDecimal numbers the same way.

Unfortunately, there isn’t a BigDecimalStream. So, we need another solution.

3. Using Reduce to Add BigDecimal Numbers

Instead of relying on sum, we can use Stream.reduce:

Stream<Integer> intNumbers = Stream.of(5, 1, 100);
int result = intNumbers.reduce(0, Integer::sum);
assertEquals(106, result);

This works on anything that can be logically added together, including BigDecimal:

Stream<BigDecimal> bigDecimalNumber = 
  Stream.of(BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN);
BigDecimal result = bigDecimalNumber.reduce(BigDecimal.ZERO, BigDecimal::add);
assertEquals(11, result);

The reduce method takes two parameters:

  • Identity – is the equivalent of 0 – it is the starting value for the reduction
  • Accumulator function – takes two parameters, the result so far, and the next element of the stream

4. Conclusion

In this article, we looked at how to find the sum of some numbers in a numeric Stream. Then we discovered how to use reduce as an alternative.

Using reduce allows us to sum a collection of BigDecimal numbers. It can be applied to any other type.

As always, the code for the examples is available over on GitHub.