对list<Eneity>进行操作

实体类:student

@Data
@EqualsAndHashCode
@AllArgsConstructor
public class Student {
   private Integer id;
   private String name;
   private String classes;
   private Integer age;
}

// 模拟数据
       List<Student> list1 = new ArrayList<>();
       list1.add(new Student(1, "zhangsan", "一班", 18));
       list1.add(new Student(2, "lisi", "二班", 20));

       List<Student> list2 = new ArrayList<>();
       list2.add(new Student(4, "zhangsan", "一班", 18));

一:在姓名,班级相同的条件下,相加年龄,将数据合并

// 合并
        List<Student> students = new ArrayList<>();
        Stream.concat(list1.stream(), list2.stream())
                .collect(
                        Collectors.groupingBy(item -> (item.getName() + item.getClasses()), 
                        Collectors.toList())
                ).forEach(
                        (key, value) -> {
                            value.stream().reduce(
                                    (a, b) -> new Student(a.getId(), a.getName(), a.getClasses(), a.getAge() + b.getAge())
                            ).ifPresent(students::add);
                        }
                );
        System.out.println("list1与list2合并:"+students);

二:使用BigDecimal求List的总数

 double sum =doubleList.stream()
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .doubleValue();

三:使用BigDecimal求List<Map<String,Double>>的总数

 Map<String, Double> dataTotal = returnList.stream()
                .flatMap(o -> o.entrySet().stream())
                .filter(entry -> entry.getValue() instanceof Double)
                .collect(Collectors.groupingBy(
                        Map.Entry::getKey,
                        //Collectors.summingDouble(entry -> (double) entry.getValue())
                        Collectors.reducing(BigDecimal.ZERO, entry -> BigDecimal.valueOf((Double) entry.getValue()), BigDecimal::add)
                )).entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry->entry.getValue().doubleValue()
                ));

四:判断实体某字段值个数

 Map<String, Long> barCodeCollect = commodityList.stream()
                .collect(Collectors.groupingBy(CommodityVO::getBarCode, Collectors.counting()));
        if (barCodeCollect.values().stream()
                .anyMatch(count -> count > 1)) {
            return AjaxResult.error("商品重复!");
        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值