java8 List sum of BigDecimal type
In Java 8, if you have a List<BigDecimal> and want to calculate the sum of all BigDecimal values in this list, you can use the Stream API's reduce method.
The reduce method accepts a binary operator that combines elements in the stream.
For BigDecimal type, you should use the add method in BigDecimal class to implement summing.
Example of summing List<BigDecimal>
import ; import ; import ; public class BigDecimalSumExample { public static void main(String[] args) { List<BigDecimal> list = ( new BigDecimal("10.5"), new BigDecimal("15.75"), new BigDecimal("20.35"), new BigDecimal("5.50") ); BigDecimal sum = () .reduce(, BigDecimal::add); ("Sum: " + sum); // Output: Sum: 52.10 } }
In this example
We first created a list containing several BigDecimal objects.
Then, we use the stream() method to convert the list into a stream, and then call the reduce method.
- The first parameter of the reduce method is the initial value of the sum (in this example)
- The second parameter is a BigDecimal::add method reference, which is used to add each element in the stream to the current value in the accumulator.
Finally, we print out the sum we get.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.