关于List<Map<String,Object>>的交集和差集

本文展示了一个Java程序,通过流(Stream)操作实现两个List<Map<String,Object>>之间的交集和差集计算。通过`Objects.equals`比较键值对并使用`collect`方法收集结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public class test {
    public static void main(String[] args) {
        //测试
        List<Map<String,Object>> sosList = new ArrayList<>();
        List<Map<String,Object>> localList = new ArrayList<>();

        //准备测试数据
        String cloumName = "id";
        int i = 7;
        for (int i1 = 0; i1 < i; i1++) {
            Map<String,Object> foo = new HashMap<>();
            foo.put("id",i1*1111);
            foo.put("name",i1*1111);

            sosList.add(foo);
            if(i1 >= 5){
                foo.put("name",i1*2222);
                localList.add(foo);
            }
        }
        System.out.println("sosList:"+sosList);
        System.out.println("localList:"+localList);
        
        //交集
        List<Map<String, Object>> updateList = localList.stream().map(map -> sosList.stream().filter(m -> Objects.equals(m.get(cloumName), map.get(cloumName))).findFirst().map(m -> { map.putAll(m);return map; }).orElse(null)).filter(Objects::nonNull).collect(Collectors.toList());
        //差集
        List<Map<String, Object>> insertList = sosList.stream().filter((mapItem) -> !localList.stream().map(item -> item.get(cloumName)).collect(Collectors.toList()).contains(mapItem.get(cloumName))).collect(Collectors.toList());
        
        System.out.println("insertList:"+insertList);
        System.out.println("updateList:"+updateList);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值