@Test public void test1(){ List<Integer> list1=new ArrayList<>(); list1.add(1); list1.add(2); list1.add(3); List<Integer> list2=new ArrayList<>(); list2.add(3); list2.add(4); list2.add(5); System.out.println("====求交集==="); List<Integer> list=list1.stream().filter(t->list2.contains(t)).collect(Collectors.toList()); list.stream().forEach(System.out::println); System.out.println("====求差集==="); list=list1.stream().filter(t-> !list2.contains(t)).collect(Collectors.toList()); list.stream().forEach(System.out::println); System.out.println("====求并集==="); list.addAll(list1); list.addAll(list2); list=list.stream().distinct().collect(Collectors.toList()); list.stream().forEach(System.out::println); }
原文:https://www.cnblogs.com/sword-successful/archive/2017/12/05/7989035.html
求并集 (降维)
@Test public void test11(){ // 例一 List<Integer> list = ImmutableList.of(1, 3, 5); list = list.stream().flatMap(l -> { List<Integer> list1 = new ArrayList<>(); list1.add(l + 1); list1.add(l + 2); return list1.stream(); }).collect(Collectors.toList()); System.out.println(list);// [2, 3, 4, 5, 6, 7] // 例二 list<map> [{a:1},{b:1},{c:1}] ==> {a:1,b:1,c:1} List<List<Map<String,Object>>> listMapMultiple = ImmutableList.of( ImmutableList.of( ImmutableMap.of("a", 1, "b", 2), ImmutableMap.of("a", 2, "b", 3) ), ImmutableList.of( ImmutableMap.of("a", 3, "b", 4), ImmutableMap.of("a", 4, "b", 5) ), ImmutableList.of( ImmutableMap.of("a", 5, "b", 6), ImmutableMap.of("a", 6, "b", 7) ) ); // 将多个list合并为一个list (降维) List<Map<String,Object>> list11 = listMapMultiple.stream().flatMap(Collection::stream).collect(Collectors.toList()); // [{a=1, b=2}, {a=2, b=3}, {a=3, b=4}, {a=4, b=5}, {a=5, b=6}, {a=6, b=7}] System.err.println("list1:"+list11); // 例二 [[1,2],[2,3,4],[5,6]] => [1,2,2,3,4,5,6] List list3 = ImmutableList.of( ImmutableList.of( ImmutableList.of("a", 1, "b", 2), ImmutableList.of("a", 2, "b", 3) ), ImmutableList.of( ImmutableList.of("a", 3, "b", 4), ImmutableList.of("a", 4, "b", 5) ), ImmutableList.of( ImmutableList.of("a", 5, "b", 6), ImmutableList.of("a", 6, "b", 7) ) ); List<? extends Serializable> collect = ImmutableList.of( ImmutableList.of("a", 5, "b", 6), ImmutableList.of("a", 6, "b", 7) ).stream().flatMap(Collection::stream).collect(Collectors.toList());// [{a=1, b=2}, {a=2, b=3}, {a=3, b=4}, {a=4, b=5}, {a=5, b=6}, {a=6, b=7}] System.err.println(collect); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?