How to Sum BigDecimal using Java 8 Stream?
In this section, we will write a Java program to Sum BigDecimal using Java 8 Stream.
We can use the Stream.reduce() to sum a list of BigDecimal.
1. Stream.reduce()
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<BigDecimal> salary = new LinkedList<>();
salary.add(BigDecimal.valueOf(2345.56));
salary.add(BigDecimal.valueOf(3149.49));
salary.add(BigDecimal.valueOf(3450.42));
salary.add(BigDecimal.valueOf(4335.54));
BigDecimal sum = salary.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println("Sum = " + sum);
}
}
Console Output:
Sum = 13281.01
2. Map & Reduce
Sum all BigDecimal
from a list of Users
.
package com.knf.dev.demo;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<User> users = Arrays.asList(
new User("a12gfd3", BigDecimal.valueOf(3459.654),
BigDecimal.valueOf(156.77)),
new User("ab1f2d3", BigDecimal.valueOf(5643.556),
BigDecimal.valueOf(100.5)),
new User("a1f2ss3", BigDecimal.valueOf(3456.888),
BigDecimal.valueOf(200)),
new User("a12sfd3", BigDecimal.valueOf(5555.99),
BigDecimal.valueOf(577.6)),
new User("fa12hj3", BigDecimal.valueOf(1234.5),
BigDecimal.valueOf(266.3))
);
BigDecimal sum = users.stream()
.map(x -> x.getSalary().add(x.getBonus())) // map
.reduce(BigDecimal.ZERO, BigDecimal::add); // reduce
System.out.println(sum);
System.out.println(sum.setScale(2, RoundingMode.HALF_UP));
}
}
class User{
private String id;
private BigDecimal salary;
private BigDecimal bonus;
public User(String id, BigDecimal salary, BigDecimal bonus) {
this.id = id;
this.salary = salary;
this.bonus = bonus;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public BigDecimal getBonus() {
return bonus;
}
public void setBonus(BigDecimal bonus) {
this.bonus = bonus;
}
}
Console Output:
20651.758
20651.76
More topics,