java 中各种类型⽤Stream 流求和
⽂章⽬录
java 中各种类型⽤Stream 流求和
⼀、BigDecimal 类型
1. 对⼀个实体类是某⼀个字段求和
2. 分组求和
数据准备
⽅式⼀
⽅式⼆
⼆、int 、double 、long 类型
1. Collectors.summarizingInt()实现
2. stream().reduce()实现
对象的⼀个字段求和 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 );
1
2
3
4
5YearNum 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);
1
2
3
4
5Map <Integer , BigDecimal > numByYear = years .stream () .collect (Collectors .groupingBy (YearNum ::getYear , Collectors .reducing (BigDecimal .ZERO , YearNum ::getNum , BigDecimal ::add )));
1
2
3Map <Integer , BigDecimal > numByYear2 = years .stream ().filter (Objects ::nonNull ).collect ( Collectors .groupingBy (YearNum ::getYear , Collectors .mapping (YearNum ::getNum , Collectors .reducing (BigDecimal .ZERO , BigDecimal ::add 1
2 List <User > userList = new ArrayList <>(Arrays .asList ( new User (1L ,new BigDecimal ("10")), new User (2L ,new BigDecimal ("100")))); DoubleSummarySt
atistics collect = userList .stream ().collect (Collectors .summarizingDouble (User ::getId )); double sum = collect .getSum ();
1
2
3
4
5
6
Long类型的集合
3. stream().mapToLong()实现
Long类型的集合
对象的⼀个字段求和 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 );1
2
3
4 List <Long > list = ListUtil .of (1L ,2L ); Long reduce = list .stream ().reduce (0L , Long ::sum );
1
2 List <Long > list = ListUtil .of (1L ,2L ); long sum = list .stream ().mapToLong (s -> s ).sum ();
1
java stream2 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 ();1
2
3
4
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论