How to Sum BigDecimal Using Stream in Java

This article discusses how to sum BigDecimal using stream. One of the significant features in Java 8 is the introduction of stream functionality and a way of carrying out the sum operation on streams of numbers like BigDecimal.

BigDecimal objects are immutable like String. Once immutable objects are created they can not be modified. So when it comes to performing arithmetic operations such as addition, multiplication, etc they are not friendly.

Sum BigDecimal in Java 5/6/7

Let’s recap, what summation or addition worked like before Java 8.

  • First, initialize the bigDecimalsList variable of data type BigDecimal List.
  • Add some BigDecimal values to it.
  • Create an object addBigDecimals to store the total sum of BigDecimal values.
  • Iterate over Array bigDecimalsList using for loop.
    • Invoke the add() method.
    • Pass a new BigDecimal object obtained from integer value form the BigDecimal from list.

Let us see the code.

Output:

15

Sum BigDecimal in Java 8

Java 8 introduces the reduce() method that covers the terminal operations such as sum, min, max, average, and count, etc individually in their own way.

You can also pass Lambda Expression in reduce() method. The identity and the accumulator is passed in reduce() method to sum an ArrayList.

The definition of the reduce() method is given below.

You can use the stream with List, Array and Map. Let us see each of them one by one.

BigDecimal sum using List

You can store the BigDecimal in a list by adding each BigDecimal as a new list element. To sum the big decimal in a list,

  • Initialize the List of BigDecimal.
  • Instead of iterating over for loop, you can use stream().reduce() method and save the sum in a variable.
  • The reduce() method accepts BigDecimal.ZERO as the identity and the BigDecimal::add as the accumulator.
  • The method returns the sum.

You can also sum using the lambda expression by following steps given below.

  • Pass the lambda expression to the reduce() method that adds two variables.
  • The reduce() method returns the resultant sum.

Let us see the code.

Output:

15
15

BigDecimal Sum Using Array

If the BigDecimal numbers are stored in an array, you can follow the given steps to get the sum.

  • Pass the array to the stream() method of the Arrays class.
  • Invoke the reduce() method by passing the BigDecimal.ZERO, and BigDecimal::add to it.
  • The method returns the sum, store it, and print it.

Let us see the code.

Output:

10.8

BigDecimal Sum Using Map

If you have stored the BigDecimal numbers in a map, you can follow the given steps to obtain the sum.

  • Invoke the values() method of the map.
  • Invoke the stream().reduce() method in chain with the values() method.
  • Pass the BigDecimal.ZERO and BigDecimal::add to the reduce() method.
  • The method returns sum of all BigDecimal values.

Let us see the code.

Output:

11.2

Stream Removes Null Values

Sometimes BigDecimal List might contain a NULL value which will raise the NullPointerException. You can resolve this issue with the help of stream.

Let us see an example where a NULL value results in an exception.

Output:

Exception in thread “main” java.lang.NullPointerException

Using a stream you can Filter NULL values to avoid this type of exception. The filter() method takes an argument and filters the elements according to it.

You can pass the Objects::nonNull filter to the filter() method.

Let us see the code.

Output:

10

Conclusion

In this article, you learned about how Java prior to version 8 can find the sum of the BigDecimal numbers. Then we discovered how java 8 uses stream to find sum of the BigDecimal numbers.

The stream can be used with List, Array & Map to find the summation. We can filter null values using stream. However, the stream can be applied with other data types as well.

This was all about how to sum BigDecimal using Stream in Java
Hope you have enjoyed reading the article. Stay tuned for more such articles.

Happy Learning!

Was this post helpful?

Related Posts

  • Java BigDecimal to Double
    17 May

    Java BigDecimal to Double

    Learn about how to convert BigDecimal to Double in java

  • 22 December

    Java BigDecimal to BigInteger

    Table of ContentsUsing BigDecimal constructorWas this post helpful? In this post, we will see how to convert

  • 19 December

    Java BigInteger to BigDecimal

    Table of ContentsUsing BigDecimal constructorWas this post helpful? In this post, we will see how to convert BigInteger toBigDecimal in java. Using BigDecimal constructor You can simply use BigDecimal’s following constructor to convert BigInteger to BigDecimal. BigDecimal(BigInteger val) Here is the complete example to convert BigInteger to BigDecimal in java. [crayon-62b864c2d41e7325115417/] When you run above […]

  • 14 December

    BigDecimal divide

    Table of ContentsSyntaxReturn typeBigDecimal round exampleWas this post helpful? In this tutorial we will see about BigDecimal‘s divide method. BigDecimal’s divide method is used to divide one BigDecimal by another. You can specify scale and rounding mode to get the output according to your need. There are 6 overloaded versions of divide method. Syntax [crayon-62b864c2d4852906987523/] […]

  • 14 December

    BigDecimal round

    Table of ContentsSyntaxReturn typeBigDecimal round exampleBigDecimal setScale methodWas this post helpful? In this tutorial, we will see about BigDecimal‘s round method. BigDecimal’s round method is used to round the BigDecimal based on MathContext setting. Syntax [crayon-62b864c2d4f90037097863/] Return type returns BigDecimal rounded with MathContext setting BigDecimal round example Let’s understand BigDecimal method with the help of […]

  • 12 October

    Java BigDecimal

    Table of ContentsConstructorsMethodsFAQsHow can you compare two BigDecimals?How to set scale in case of BigDecimalsHow to convert String to BigDecimal?How to convert BigDecimal to String?How to add two BigDecimals in java?How to subtract two BigDecimals in java?How to multiply two BigDecimals in java?How to divide two BigDecimals in java?How to remove trailing zero from BigDecimal?Was […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.