【JAVA 求差集】

两个list求差集

求差集返回 list字段

/**
 * 差集(基于API解法) 适用于小数据量
 * 求List1中有的但是List2中没有的元素
 * 时间复杂度 O(list1.size() * list2.size())
 */
public static List<String> subList(List<String> list1, List<String> list2) {
    list1.removeAll(list2);
    return list1;
}
 
/**
 * 差集(基于常规解法)优化解法1 适用于中等数据量
 * 求List1中有的但是List2中没有的元素
 * 空间换时间降低时间复杂度
 * 时间复杂度O(Max(list1.size(),list2.size()))
 */
public static List<String> subList1(List<String> list1, List<String> list2) {
    //空间换时间 降低时间复杂度
    Map<String, String> tempMap = new HashMap<>();
    for(String str:list2){
        tempMap.put(str,str);
    }
    //LinkedList 频繁添加删除 也可以ArrayList容量初始化为List1.size(),防止数据量过大时频繁扩容以及数组复制
    List<String> resList = new LinkedList<>();
    for(String str:list1){
        if(!tempMap.containsKey(str)){
            resList.add(str);
        }
    }
    return resList;
}
 
/**
 * 差集(基于java8新特性)优化解法2 适用于大数据量
 * 求List1中有的但是List2中没有的元素
 */
public static List<String> subList2(List<String> list1, List<String> list2) {
    Map<String, String> tempMap = list2.parallelStream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldData, newData) -> newData));
    return list1.parallelStream().filter(str->{
        return !tempMap.containsKey(str);
    }).collect(Collectors.toList());
}

求差集返回 list对象

 //查询所有的数据 也就是查询数据多的list
List<ApplicationAttributePo> unionAttributePoList = attributeService.attrList(appid, attributenameLike, attributegroupnameLike);
        if (CollectionUtils.isEmpty(unionAttributePoList)) {
            return Collections.emptyList();
        }
        // 去除默认属性  需要过滤掉的list
        List<String> defaultCodeList = attributeService.getDefaultCode();
		//必须要将这个list转为set !!!
        Set<String> codeSet = new HashSet<>(defaultCodeList);
		
		//求unionAttributePoList中有的但是codeSet中没有的元素
        List<ApplicationAttributePo> attributePoList = unionAttributePoList.stream()
                .filter(item -> !codeSet.contains(item.getAttributecode()))
                .collect(Collectors.toList());
		
		//这里是做一个转换
        List<ApplicationAttributeVo> attributeVoList = attributePoList.stream().map(attribute -> {
            ApplicationAttributeVo applicationAttributeVo = new ApplicationAttributeVo();
            BeanUtils.copyProperties(attribute, applicationAttributeVo);
            return applicationAttributeVo;
        }).collect(Collectors.toList());

        return attributeVoList;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值