List<User> userList = new ArrayList<>(Arrays.asList(
new User(1,new BigDecimal("10")),
new User(2,new BigDecimal("100"))));
BigDecimal sum = userList.stream().filter(Objects::nonNull).map(User::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
数据准备
YearNum yearNum1 = new YearNum(2021, BigDecimal.valueOf(10));
YearNum yearNum11 = new YearNum(2021, BigDecimal.valueOf(10));
YearNum yearNum2 = new YearNum(2022, BigDecimal.valueOf(20));
YearNum yearNum22 = new YearNum(2022, BigDecimal.valueOf(20));
List<YearNum> years = ListUtil.of(yearNum1, yearNum11, yearNum2, yearNum22);
方式一
Map<Integer, BigDecimal> numByYear = years.stream()
.collect(Collectors.groupingBy(YearNum::getYear,
Collectors.reducing(BigDecimal.ZERO, YearNum::getNum, BigDecimal::add)));
方式二
Map<Integer, BigDecimal> numByYear2 = years.stream().filter(Objects::nonNull).collect(
Collectors.groupingBy(YearNum::getYear, Collectors.mapping(YearNum::getNum, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
List<User> userList = new ArrayList<>(Arrays.asList(
new User(1L,new BigDecimal("10")),
new User(2L,new BigDecimal("100"))));
DoubleSummaryStatistics collect = userList.stream().collect(Collectors.summarizingDouble(User::getId));
double sum = collect.getSum();
对象的一个字段求和
List<User> userList = new ArrayList<>(Arrays.asList(
new User(1L,new BigDecimal("10")),
new User(2L,new BigDecimal("100"))));
Long reduce = userList.stream().filter(Objects::nonNull).map(User::getId).reduce(0L, Long::sum);
Long类型的集合
List<Long> list = ListUtil.of(1L,2L);
Long reduce = list.stream().reduce(0L, Long::sum);
Long类型的集合
List<Long> list = ListUtil.of(1L,2L);
long sum = list.stream().mapToLong(s -> s).sum();
对象的一个字段求和
List<User> userList = new ArrayList<>(Arrays.asList(
new User(1L,new BigDecimal("10")),
new User(2L,new BigDecimal("100"))));
long sum = userList.stream().mapToLong(User::getId).sum();
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_43296313/article/details/122600324
内容来源于网络,如有侵权,请联系作者删除!