LoginSignup
0
2

More than 3 years have passed since last update.

streamを使ってBigDecimalの計算をする - sum編 -

Posted at

基本構文


List<BigDecimal> heightList = Arrays.asList(new BigDecimal("70.20"), new BigDecimal("80.12"));
BigDecimal sum = hogeList.stream.reduce(BigDecimal.ZERO, BigDecimal::add);

オブジェクト内のBigDecimalの合計

class Person {
    private final String name;
    private final BigDecimal weight;

    Person(String name, BigDecimal weight) {
        this.name = name;
        this.weight = weight;
    }

    public BigDecimal getWeight() {
        return this.weight;
    }

}

public class Main {
    public static void main(String[] args) throws Exception {
        Person p1 = new Person("太郎", new BigDecimal("72.1"));
        Person p2 = new Person("二郎", new BigDecimal("79.1"));

        List<Person> personList = Arrays.asList(p1, p2);

        BigDecimal totalWeight = personList.stream().map(Person::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);

        System.out.println(totalWeight);

    }
}

おまけ utilクラスを作ろうと思うと

public class Main {
    public static void main(String[] args) throws Exception {
        Person p1 = new Person("太郎", new BigDecimal("72.1"));
        Person p2 = new Person("二郎", new BigDecimal("79.1"));

        List<Person> personList = Arrays.asList(p1, p2);

        BigDecimal totalWeight = sumBigDecimal(personList, Person::getWeight);

        System.out.println(totalWeight);

    }

    public static <T> BigDecimal sumBigDecimal(List<T> list, Function<T, BigDecimal> mapper) {
        return list.stream().map(mapper).reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2