Java 集合操作之交集、并集和差集

简介: 在 Java 编程中,经常需要对集合进行一些操作,比如取两个集合的交集、并集和差集。本文将介绍如何使用 Java 集合框架中的方法来实现这些集合操作,并通过源码解析来深入了解其实现原理。


_20230704224850.png
在 Java 编程中,经常需要对集合进行一些操作,比如取两个集合的交集、并集和差集。本文将介绍如何使用 Java 集合框架中的方法来实现这些集合操作,并通过源码解析来深入了解其实现原理。

先上代码
java import lombok.extern.slf4j.Slf4j; import java.util.*; @Slf4j public class Test { public static void main(String[] args) { System.out.println("===============Set================="); Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4)); Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6)); // 交集 Set<Integer> intersectionSet = new HashSet<>(set1); intersectionSet.retainAll(set2); System.out.println("交集:" + intersectionSet); // 并集 Set<Integer> unionSet = new HashSet<>(set1); unionSet.addAll(set2); System.out.println("并集:" + unionSet); // 差集 Set<Integer> differenceSet = new HashSet<>(set1); differenceSet.removeAll(set2); System.out.println("差集:" + differenceSet); System.out.println("===============List================="); List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4)); List<Integer> list2= new ArrayList<>(Arrays.asList(3, 4, 5, 6)); // 交集 List<Integer> intersectionList = new ArrayList<>(list1); intersectionList.retainAll(list2); System.out.println("交集:" + intersectionSet); // 并集 List<Integer> unionList = new ArrayList<>(list1); unionList.addAll(list2); System.out.println("并集:" + unionList); // 差集 List<Integer> differenceList = new ArrayList<>(list1); differenceList.removeAll(list2); System.out.println("差集:" + differenceList); } }

执行结果
===============Set================= 交集:[3, 4] 并集:[1, 2, 3, 4, 5, 6] 差集:[1, 2] ===============List================= 交集:[3, 4] 并集:[1, 2, 3, 4, 3, 4, 5, 6] 差集:[1, 2]

此处各操作会改动原始集合,所以此处的操作都是创建了一个新的集合来执行操作


1. 交集(Intersection):

交集是指两个集合中共有的元素集合。在 Java 中,可以使用 retainAll 方法来实现两个集合的交集操作。retainAll 方法会修改调用该方法的集合,使其只包含与指定集合共有的元素

源码解析:

- Set

在AbstractCollection的 retainAll 方法的内部实现中,通常会遍历调用该方法的集合,并逐个判断元素是否存在于指定集合中。如果元素不存在于指定集合,则通过迭代器的 remove 方法将其从集合中删除。这样就实现了只保留共有元素的操作。

java public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); boolean modified = false; Iterator<E> it = iterator(); while (it.hasNext()) { if (!c.contains(it.next())) { it.remove(); modified = true; } } return modified; }

- ArrayList

java public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); } private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }


2. 并集(Union):
并集是指将两个集合中的所有元素合并到一个新的集合中。在 Java 中,可以使用 addAll 方法来实现两个集合的并集操作。addAll 方法会将指定集合中的所有元素添加到调用该方法的集合中。

- Set

addAll 方法的内部实现会遍历指定集合,并逐个将元素添加到调用该方法的集合中。如果被添加的元素已经存在于集合中,则不会重复添加。

java public boolean addAll(Collection<? extends E> c) { boolean modified = false; for (E e : c) if (add(e)) modified = true; return modified; }

- ArrayList

java public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; }

3. 差集(Difference):
差集是指从一个集合中移除另一个集合中相同的元素后的剩余元素集合。在 Java 中,可以使用 removeAll 方法来实现两个集合的差集操作。removeAll 方法会修改调用该方法的集合,移除与指定集合相同的元素。
- Set
在 removeAll 方法的内部实现中,通常会遍历指定集合,并逐个判断元素是否存在于调用该方法的集合中。如果元素存在于调用的集合中,则通过迭代器的 remove 方法将其从集合中移除。这样就实现了移除与指定集合相同元素的操作。

java public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); boolean modified = false; Iterator<?> it = iterator(); while (it.hasNext()) { if (c.contains(it.next())) { it.remove(); modified = true; } } return modified; }

- ArrayList

java public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, false); } /** * Retains only the elements in this list that are contained in the * specified collection. In other words, removes from this list all * of its elements that are not contained in the specified collection. * * @param c collection containing elements to be retained in this list * @return {@code true} if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>), * or if the specified collection is null * @see Collection#contains(Object) */ public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); } private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }


本文介绍了在 Java 中实现集合的交集、并集和差集操作的方法,并通过源码解析来深入了解其实现原理。这些集合操作在实际开发中经常使用,可以帮助我们处理集合数据,快速进行元素筛选和计算。掌握这些操作可以提高代码的效率和可读性。



目录
相关文章
|
12天前
|
Java 大数据 API
Java Stream API:现代集合处理与函数式编程
Java Stream API:现代集合处理与函数式编程
174 100
|
12天前
|
Java API 数据处理
Java Stream API:现代集合处理新方式
Java Stream API:现代集合处理新方式
176 101
|
17天前
|
存储 Java Go
对比Java学习Go——函数、集合和OOP
Go语言的函数支持声明与调用,具备多返回值、命名返回值等特性,结合`func`关键字与类型后置语法,使函数定义简洁直观。函数可作为一等公民传递、赋值或作为参数,支持匿名函数与闭包。Go通过组合与接口实现面向对象编程,结构体定义数据,方法定义行为,接口实现多态,体现了Go语言的简洁与高效设计。
|
25天前
|
算法 Java
50道java集合面试题
50道 java 集合面试题
|
2月前
|
存储 NoSQL Java
Java Stream API:集合操作与并行处理
Stream API 是 Java 8 提供的集合处理工具,通过声明式编程简化数据操作。它支持链式调用、延迟执行和并行处理,能够高效实现过滤、转换、聚合等操作,提升代码可读性和性能。
|
2月前
|
存储 缓存 安全
Java集合框架(三):Map体系与ConcurrentHashMap
本文深入解析Java中Map接口体系及其实现类,包括HashMap、ConcurrentHashMap等的工作原理与线程安全机制。内容涵盖哈希冲突解决、扩容策略、并发优化,以及不同Map实现的适用场景,助你掌握高并发编程核心技巧。
|
2月前
|
存储 缓存 安全
Java集合框架(二):Set接口与哈希表原理
本文深入解析Java中Set集合的工作原理及其实现机制,涵盖HashSet、LinkedHashSet和TreeSet三大实现类。从Set接口的特性出发,对比List理解去重机制,并详解哈希表原理、hashCode与equals方法的作用。进一步剖析HashSet的底层HashMap实现、LinkedHashSet的双向链表维护顺序特性,以及TreeSet基于红黑树的排序功能。文章还包含性能对比、自定义对象去重、集合运算实战和线程安全方案,帮助读者全面掌握Set的应用与选择策略。
150 23
|
2月前
|
存储 安全 Java
Java集合框架(一):List接口及其实现类剖析
本文深入解析Java中List集合的实现原理,涵盖ArrayList的动态数组机制、LinkedList的链表结构、Vector与Stack的线程安全性及其不推荐使用的原因,对比了不同实现的性能与适用场景,帮助开发者根据实际需求选择合适的List实现。
|
2月前
|
安全 Java 开发者
Java集合框架:详解Deque接口的栈操作方法全集
理解和掌握这些方法对于实现像浏览器后退功能这样的栈操作来说至关重要,它们能够帮助开发者编写既高效又稳定的应用程序。此外,在多线程环境中想保证线程安全,可以考虑使用ConcurrentLinkedDeque,它是Deque的线程安全版本,尽管它并未直接实现栈操作的方法,但是Deque的接口方法可以相对应地使用。
123 12
|
3月前
|
存储 缓存 NoSQL
java 集合入门基础理论的核心概念与实用长尾知识
本文介绍了Java集合框架的基础理论知识,包括单列集合(List、Set、Queue)和双列集合(Map)的特点及常用实现类(如ArrayList、HashSet、HashMap等)。详细讲解了集合的遍历方式(迭代器、增强for循环、Lambda表达式)和典型应用场景(如数据去重、键值存储等)。通过具体代码示例,帮助初学者理解集合框架的核心概念和实际应用,为Java编程中的数据存储与管理提供基础指导。
97 0