Help us understand the problem. What is going on with this article?

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

基本構文

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);
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした