可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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:
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
回答2:
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