CollectionUtils工具类之并集union(arr1,arr2)和差集subtract(arr1,arr2)
一、CollectionUtils工具类之并集union(arr1,arr2)和差集subtract(arr1,arr2)
采用的类:
import org.apache.commons.collections4.CollectionUtils;
①并集union(arr1,arr2)
这是将两个集合加在一起,然后去重
List<Integer> orderList1 = Arrays.asList(1, 2, 3); List<Integer> orderList2 = Arrays.asList(3, 4, 5); List<Integer> union = new ArrayList<>(CollectionUtils.union(orderList1, orderList2)); // 1,2,3,4,5 System.out.println("union = " + union);
②差集subtract(arr1,arr2)
这是将两个集合的差,如1,2,3 差集3,4,5就会得到1,2,将3这个重复的去掉
List<Integer> orderList1 = Arrays.asList(1, 2, 3); List<Integer> orderList2 = Arrays.asList(3, 4, 5); List<Integer> subtract = new ArrayList<>(CollectionUtils.subtract (orderList1, orderList2)); // 1,2 System.out.println("subtract = " + subtract );
③遇到的问题
返回值是父级的Collection<O>,这样的话如果只想做合并去重的话就会导致类型不一致,而照成麻烦
List<Integer> orderList1 = Arrays.asList(1, 2, 3); List<Integer> orderList2 = Arrays.asList(3, 4, 5);
Collection<Integer> union = CollectionUtils.union(orderList1, orderList2);
// 1,2,3,4,5 System.out.println("union = " + union);
如需要转换为对应的类型,如上转回List<Integer>可以有几种方案
方案1
List<Integer> union = new ArrayList<>(CollectionUtils.union(orderList1, orderList2));
方案2
// 这个会警告,我们这里是加了一个.distinct()做过度
List<Integer> union1 = CollectionUtils.union(orderList1, orderList2).stream().collect(Collectors.toList());
* 博客文章部分截图及内容来自于学习的书本及相应培训课程,仅做学习讨论之用,不做商业用途。
* 如有侵权,马上联系我,我立马删除对应链接。
* 备注:王先生
* 我的网易邮箱:wzw_1314_520@163.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
2021-01-27 SQL语句之Column 'Status' in where clause is ambiguous错误