java 集合取交集

1.使用retainAll()方法:

List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));

List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 3, 4));

list1.retainAll(list2);

System.out.println(list1); // 输出 2, 3

Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3));

Set<Integer> set2 = new HashSet<>(Arrays.asList(2, 3, 4));

set1.retainAll(set2);

System.out.println(set1); // 输出 2, 3

2.使用Java 8的stream的filter方法和collect方法:

List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 3, 4));
List<Integer> intersection = list1.stream().filter(e -> list2.contains(e)).collect(Collectors.toList());
System.out.println(intersection); // 输出 2, 3

相关推荐
非优秀程序员7 小时前
第04章 邮箱大战,163 与 QQ 的暗战|《互联网产品恩仇录》
java·vue.js·架构
知已难寻8 小时前
Docker 入门:容器技术与 Docker 基础
java·运维·服务器·docker·云原生·容器
沐晓时光8 小时前
C语言入门,内存函数知识讲解
c语言·开发语言
文丑颜不良啊10 小时前
LeetCode2481~2500题目解析
java·leetcode
Flynn Liang11 小时前
同一需求三套写法:用 Spring AI、LangChain4j、AgentScope Java 各实现一个带工具调用的 RAG 助手(实战对比)
java·人工智能·大模型·架构设计·spring ai·langchain4j·agentscope
聪明的笨猪猪11 小时前
实际工程问题:AI 生成 Spring Cache(@Cacheable / @CachePut / @CacheEvict)缓存注解踩坑
java·经验分享·面试·ai编程
愿有所息12 小时前
记一次 ARM64 + JDK8 上 fastjson2 的诡异数据错乱
java
秋饼12 小时前
MCP 2026-07-28 无状态协议大改版:Spring AI 2.1 多轮往返请求与网关路由落地
java·ai·技术分享·后端开发
SL_staff13 小时前
JVS-BI 实战:业务人员如何用零代码 ELT + 可视化配置构建实时经营分析闭环
java·spring·全栈
SL_staff14 小时前
企业AI落地难?JVS-AI渐进式实践:安全可控、小切口验证、标准化沉淀与规模化复制
java·开源·aigc