java中各种类型用Stream流求和

x33g5p2x  于2022-02-07 转载在 Java  
字(2.0k)|赞(0)|评价(0)|浏览(1081)

java中各种类型用Stream流求和

一、BigDecimal类型

1. 对一个实体类是某一个字段求和

  1. List<User> userList = new ArrayList<>(Arrays.asList(
  2. new User(1,new BigDecimal("10")),
  3. new User(2,new BigDecimal("100"))));
  4. BigDecimal sum = userList.stream().filter(Objects::nonNull).map(User::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

2. 分组求和

数据准备

  1. YearNum yearNum1 = new YearNum(2021, BigDecimal.valueOf(10));
  2. YearNum yearNum11 = new YearNum(2021, BigDecimal.valueOf(10));
  3. YearNum yearNum2 = new YearNum(2022, BigDecimal.valueOf(20));
  4. YearNum yearNum22 = new YearNum(2022, BigDecimal.valueOf(20));
  5. List<YearNum> years = ListUtil.of(yearNum1, yearNum11, yearNum2, yearNum22);

方式一

  1. Map<Integer, BigDecimal> numByYear = years.stream()
  2. .collect(Collectors.groupingBy(YearNum::getYear,
  3. Collectors.reducing(BigDecimal.ZERO, YearNum::getNum, BigDecimal::add)));

方式二

  1. Map<Integer, BigDecimal> numByYear2 = years.stream().filter(Objects::nonNull).collect(
  2. Collectors.groupingBy(YearNum::getYear, Collectors.mapping(YearNum::getNum, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));

二、int、double、long类型

1. Collectors.summarizingInt()实现

  1. List<User> userList = new ArrayList<>(Arrays.asList(
  2. new User(1L,new BigDecimal("10")),
  3. new User(2L,new BigDecimal("100"))));
  4. DoubleSummaryStatistics collect = userList.stream().collect(Collectors.summarizingDouble(User::getId));
  5. double sum = collect.getSum();

2. stream().reduce()实现

对象的一个字段求和

  1. List<User> userList = new ArrayList<>(Arrays.asList(
  2. new User(1L,new BigDecimal("10")),
  3. new User(2L,new BigDecimal("100"))));
  4. Long reduce = userList.stream().filter(Objects::nonNull).map(User::getId).reduce(0L, Long::sum);

Long类型的集合

  1. List<Long> list = ListUtil.of(1L,2L);
  2. Long reduce = list.stream().reduce(0L, Long::sum);

3. stream().mapToLong()实现

Long类型的集合

  1. List<Long> list = ListUtil.of(1L,2L);
  2. long sum = list.stream().mapToLong(s -> s).sum();

对象的一个字段求和

  1. List<User> userList = new ArrayList<>(Arrays.asList(
  2. new User(1L,new BigDecimal("10")),
  3. new User(2L,new BigDecimal("100"))));
  4. long sum = userList.stream().mapToLong(User::getId).sum();

相关文章

最新文章

更多