标签:交集 deptList2 List 差集 deptList1 Dept add 集合 new
正常的集合取交集操作
如下代码示例:
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;
标签:交集,deptList2,List,差集,deptList1,Dept,add,集合,new 来源: https://blog.csdn.net/weixin_44632065/article/details/120410237
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。