Java 8 – How to Sum BigDecimal using Stream

Introduction

Summing numbers is a common task in Java, and with Java 8's Stream API, you can perform summing operations in a more functional and concise way. While summing primitive types like int or double is straightforward, summing objects like BigDecimal requires some additional steps. BigDecimal is typically used for calculations involving high precision, such as in financial applications.

In this guide, we will explore how to sum BigDecimal values using the Stream API in Java 8.

Solution Steps

  1. Define the List of BigDecimal Values: Create a list containing BigDecimal values.
  2. Use Stream's reduce() Method: Apply the reduce() method to sum the values. BigDecimal requires the use of its add() method for summation.
  3. Handle Empty Lists: Provide a default value to avoid issues with empty lists.

Java Program

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

public class SumBigDecimalUsingStream {
    public static void main(String[] args) {
        // Step 1: Define a list of BigDecimal values
        List<BigDecimal> amounts = Arrays.asList(
            new BigDecimal("100.50"),
            new BigDecimal("200.75"),
            new BigDecimal("300.25"),
            new BigDecimal("150.00")
        );

        // Step 2: Sum the BigDecimal values using Stream's reduce() method
        BigDecimal totalSum = amounts.stream()
            .reduce(BigDecimal.ZERO, BigDecimal::add);  // Summing with BigDecimal's add()

        // Step 3: Display the total sum
        System.out.println("Total Sum: " + totalSum);
    }
}

Output

Total Sum: 751.50

Explanation

Step 1: Define the List of BigDecimal Values

We first define a list of BigDecimal values that we want to sum:

List<BigDecimal> amounts = Arrays.asList(
    new BigDecimal("100.50"),
    new BigDecimal("200.75"),
    new BigDecimal("300.25"),
    new BigDecimal("150.00")
);

The values in the list are instances of BigDecimal initialized with high precision values.

Step 2: Sum the Values Using Stream's reduce()

We use the reduce() method to sum the values:

BigDecimal totalSum = amounts.stream()
    .reduce(BigDecimal.ZERO, BigDecimal::add);
  • BigDecimal.ZERO: This is the initial value used as the identity element for summing.
  • BigDecimal::add: This is a method reference to the add() method of BigDecimal, which is used to sum the elements.

Step 3: Display the Total Sum

We print the sum of the BigDecimal values:

System.out.println("Total Sum: " + totalSum);

Conclusion

Summing BigDecimal values using Java 8 Streams is simple and efficient with the reduce() method. By providing BigDecimal.ZERO as the identity value and using the add() method, you can sum large and precise values in a clean and functional way. This approach is especially useful in financial or high-precision applications where BigDecimal is commonly used.

Comments