Skip to content
Home » Java Stream reduce BigDecimal

Java Stream reduce BigDecimal

  • by
Java Stream reduce to different type

1. Overview

In this article, we will make use of the Java stream – the general-purpose method reduce to sum BigDecimal values. Java BigDecimal is an immutable, arbitrary-precision signed decimal number.

2. Java BigDecimal

We use Java BigDeicmal for high-precision arithmetic operations like summing up monetary balances where we expect precise output and even minor deviations could lead to a huge impact.

The arbitrary-precision means that the BigDecimal uses as much space as required to save the whole value.

With arbitrary precision integers, the integers can be as large as you need (“arbitrarily large”) and the library will keep all the digits down to the least significant unit. Instead, limited by the amount of memory that your server can hold.

2. Java stream sum BigDecimal values

When you want to sum two BigDecimal integers, you would have given as below:

BigDecimal a = new BigDecimal(String.valueOf(10.0));
BigDecimal b = new BigDecimal(String.valueOf(10.0));
BigDecimal result = a.add(b);

2.1. Java stream reduce BigDecimal

Now, if you want to sum a list of BigDecimal integers, you can implement as below with Java streams:

BigDecimal result = list.stream()
        .reduce(BigDecimal.ZERO, BigDecimal::add);

(or)
BigDecimal sum = values.stream().reduce((x, y) -> x.add(y)).get();

If you have a list of Double values and want to convert it to BigDecimal before summing them up, you can use map method to convert double to BigDecimal.

BigDecimal result = list.stream().map(x -> new BigDecimal(String.valueOf(x)))
             .reduce(BigDecimal.ZERO, BigDecimal::add);

We recommend you, first convert the double value to a string and then use the BigDecimal’s string constructor. In this way, you don’t lose any precision.

2.2. Java stream reusable collector

Java Collector is the utility class that provides many helpful methods and functions for the collector interface. We mainly use the collector implementation with the stream collect() method.

You can sum up the values of a BigDecimal stream using a reusable reduction operator Collector named summingBigDecimal:

BigDecimal sum = bigDecimalStream.collect(summingBigDecimal());

You can implement the Collector as below:

public static Collector<BigDecimal, ?, BigDecimal> summingBigDecimal() {
    return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}

4. Conclusion

In this article, we have seen the various forms of summing up the BigDecimal integers and receiving the result with high precision. If you are interested in other Java stream features, refer to these articles.

For code samples, you can refer to our GitHub repository.

Leave a Reply

Your email address will not be published. Required fields are marked *