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

正常的集合取交集操作

如下代码示例:

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;
上一篇:数组[切片]、字典、函数


下一篇:笔记:STL学习(二)-- 迭代器和traits