sum of BigDecimal List using streams and sum method

时光怂恿深爱的人放手 提交于 2020-01-02 13:44:23

问题


If we have all int or long or other primitive datatype value in list then we obtain sun of all values using

return items.stream().mapToInt(i -> i).sum();

I have list of BigDecimal values,how to find the sum of all values using Java8

As there is no default method like mapToBigDecimal I tried to create plain map but then I cannot use sum()


回答1:


List<BigDecimal> items = Arrays.asList(BigDecimal.ONE, BigDecimal.valueOf(1.5), BigDecimal.valueOf(100));
items.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

Though Answer provided by Lisq199 works but I am in favor of including Holger and Klitos comments,This handles No values and always returns a value




回答2:


You can use Stream#reduce(BinaryOperator).

A simple example:

List<BigDecimal> items = Arrays.asList(BigDecimal.ONE, BigDecimal.valueOf(1.5), BigDecimal.valueOf(100));
items.stream().reduce((i, j) -> i.add(j)).ifPresent(System.out::println);
// Outputs 102.5


来源:https://stackoverflow.com/questions/41966808/sum-of-bigdecimal-list-using-streams-and-sum-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!