集合的交集和差集优化(代码层面)

正常的集合取交集操作

如下代码示例:

public class Test {
  
    public static void main(String[] args) {
       //自定义的对象,Dept部门实体类
        List<Dept> deptList1  = new ArrayList<Dept>();
        deptList1.add(new Dept(190,"销售部","learn"));
        deptList1.add(new Dept(192,"财务部","learn"));
        deptList1.add(new Dept(191,"运营部","learn"));
        deptList1.add(new Dept(193,"组织部","learn"));

        List<Dept> deptList2  = new ArrayList<Dept>();
        deptList2.add(new Dept(190,"销售部","learn"));
        deptList2.add(new Dept(192,"财务部","learn"));
        deptList2.add(new Dept(191,"运营部","learn"));
        deptList2.add(new Dept(193,"组织部","learn"));
        deptList2.add(new Dept(194,"人事部","learn"));
        List<Dept>  intersection = getIntersection(deptList1,deptList2);
        for (Dept dept:intersection) {
            System.out.println(dept.toString());
        }

        List<Dept>  difference = getDifference(deptList2,deptList1);
        System.out.println(difference.size());
        for (Dept dept:difference) {
            System.out.println("差集"+dept.toString());
        }
    }
   //取交集,通过no
    public static List<Dept> getIntersection(List<Dept> deptList1, List<Dept> deptList2){
        List<Dept>  intersection = deptList1.stream()
                .filter(item -> deptList2.stream().map(e -> e.getDeptNo())
                        .collect(Collectors.toList()).contains(item.getDeptNo()))
                .collect(Collectors.toList());
      return  intersection;
    }
     //取差集,通过no
    public static  List<Dept> getDifference(List<Dept> deptList1,List<Dept>deptList2){
        List<Dept>  difference = deptList1.stream()
                .filter(item -> !deptList2.stream().map(e -> e.getDeptNo())
                        .collect(Collectors.toList()).contains(item.getDeptNo()))
                .collect(Collectors.toList());
        return difference;
    }
}

然后是优化后的,就是要将其中的内循环给拿出来,Set进行比较的效率更高,且没有双循环。

public static List<Dept> getIntersection(List<Dept> deptList1, List<Dept> deptList2){
Set<Long> s = deptList2.stream().map(e -> e.getDeptNo())
                        .collect(Collectors.toSet())
        List<Dept>  intersection = deptList1.stream()
                .filter(item -> s.contains(item.getDeptNo()))
                .collect(Collectors.toList());
      return  intersection;
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值