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

淩亂°似流年 2023-10-13 11:39 136阅读 0赞

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

先上代码

  1. import lombok.extern.slf4j.Slf4j;
  2. import java.util.*;
  3. @Slf4j
  4. public class Test
  5. {
  6. public static void main(String[] args) {
  7. System.out.println("===============Set=================");
  8. Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));
  9. Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));
  10. // 交集
  11. Set<Integer> intersectionSet = new HashSet<>(set1);
  12. intersectionSet.retainAll(set2);
  13. System.out.println("交集:" + intersectionSet);
  14. // 并集
  15. Set<Integer> unionSet = new HashSet<>(set1);
  16. unionSet.addAll(set2);
  17. System.out.println("并集:" + unionSet);
  18. // 差集
  19. Set<Integer> differenceSet = new HashSet<>(set1);
  20. differenceSet.removeAll(set2);
  21. System.out.println("差集:" + differenceSet);
  22. System.out.println("===============List=================");
  23. List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
  24. List<Integer> list2= new ArrayList<>(Arrays.asList(3, 4, 5, 6));
  25. // 交集
  26. List<Integer> intersectionList = new ArrayList<>(list1);
  27. intersectionList.retainAll(list2);
  28. System.out.println("交集:" + intersectionSet);
  29. // 并集
  30. List<Integer> unionList = new ArrayList<>(list1);
  31. unionList.addAll(list2);
  32. System.out.println("并集:" + unionList);
  33. // 差集
  34. List<Integer> differenceList = new ArrayList<>(list1);
  35. differenceList.removeAll(list2);
  36. System.out.println("差集:" + differenceList);
  37. }
  38. }

执行结果

  1. ===============Set=================
  2. 交集:[3, 4]
  3. 并集:[1, 2, 3, 4, 5, 6]
  4. 差集:[1, 2]
  5. ===============List=================
  6. 交集:[3, 4]
  7. 并集:[1, 2, 3, 4, 3, 4, 5, 6]
  8. 差集:[1, 2]

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

  1. 交集(Intersection):

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

源码解析:

  • Set

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

  1. public boolean retainAll(Collection<?> c) {
  2. Objects.requireNonNull(c);
  3. boolean modified = false;
  4. Iterator<E> it = iterator();
  5. while (it.hasNext()) {
  6. if (!c.contains(it.next())) {
  7. it.remove();
  8. modified = true;
  9. }
  10. }
  11. return modified;
  12. }
  • ArrayList

    public boolean retainAll(Collection<?> c) {

    1. Objects.requireNonNull(c);
    2. return batchRemove(c, true);
    3. }
    4. private boolean batchRemove(Collection<?> c, boolean complement) {
    5. final Object[] elementData = this.elementData;
    6. int r = 0, w = 0;
    7. boolean modified = false;
    8. try {
    9. for (; r < size; r++)
    10. if (c.contains(elementData[r]) == complement)
    11. elementData[w++] = elementData[r];
    12. } finally {
    13. // Preserve behavioral compatibility with AbstractCollection,
    14. // even if c.contains() throws.
    15. if (r != size) {
    16. System.arraycopy(elementData, r,
    17. elementData, w,
    18. size - r);
    19. w += size - r;
    20. }
    21. if (w != size) {
    22. // clear to let GC do its work
    23. for (int i = w; i < size; i++)
    24. elementData[i] = null;
    25. modCount += size - w;
    26. size = w;
    27. modified = true;
    28. }
    29. }
    30. return modified;
    31. }
  1. 并集(Union):
    并集是指将两个集合中的所有元素合并到一个新的集合中。在 Java 中,可以使用 addAll 方法来实现两个集合的并集操作。addAll 方法会将指定集合中的所有元素添加到调用该方法的集合中。

    • Set

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

  1. public boolean addAll(Collection<? extends E> c) {
  2. boolean modified = false;
  3. for (E e : c)
  4. if (add(e))
  5. modified = true;
  6. return modified;
  7. }
  • ArrayList

    public boolean addAll(Collection<? extends E> c) {

    1. Object[] a = c.toArray();
    2. int numNew = a.length;
    3. ensureCapacityInternal(size + numNew); // Increments modCount
    4. System.arraycopy(a, 0, elementData, size, numNew);
    5. size += numNew;
    6. return numNew != 0;
    7. }
  1. 差集(Difference):
    差集是指从一个集合中移除另一个集合中相同的元素后的剩余元素集合。在 Java 中,可以使用 removeAll 方法来实现两个集合的差集操作。removeAll 方法会修改调用该方法的集合,移除与指定集合相同的元素。

    • Set
      在 removeAll 方法的内部实现中,通常会遍历指定集合,并逐个判断元素是否存在于调用该方法的集合中。如果元素存在于调用的集合中,则通过迭代器的 remove 方法将其从集合中移除。这样就实现了移除与指定集合相同元素的操作。

    public boolean removeAll(Collection<?> c) {

    1. Objects.requireNonNull(c);
    2. boolean modified = false;
    3. Iterator<?> it = iterator();
    4. while (it.hasNext()) {
    5. if (c.contains(it.next())) {
    6. it.remove();
    7. modified = true;
    8. }
    9. }
    10. return modified;
    11. }
    • ArrayList

    public boolean removeAll(Collection<?> c) {

    1. Objects.requireNonNull(c);
    2. return batchRemove(c, false);
    3. }
    4. /**
    5. * Retains only the elements in this list that are contained in the
    6. * specified collection. In other words, removes from this list all
    7. * of its elements that are not contained in the specified collection.
    8. *
    9. * @param c collection containing elements to be retained in this list
    10. * @return {@code true} if this list changed as a result of the call
    11. * @throws ClassCastException if the class of an element of this list
    12. * is incompatible with the specified collection
    13. * (<a href="Collection.html#optional-restrictions">optional</a>)
    14. * @throws NullPointerException if this list contains a null element and the
    15. * specified collection does not permit null elements
    16. * (<a href="Collection.html#optional-restrictions">optional</a>),
    17. * or if the specified collection is null
    18. * @see Collection#contains(Object)
    19. */
    20. public boolean retainAll(Collection<?> c) {
    21. Objects.requireNonNull(c);
    22. return batchRemove(c, true);
    23. }
    24. private boolean batchRemove(Collection<?> c, boolean complement) {
    25. final Object[] elementData = this.elementData;
    26. int r = 0, w = 0;
    27. boolean modified = false;
    28. try {
    29. for (; r < size; r++)
    30. if (c.contains(elementData[r]) == complement)
    31. elementData[w++] = elementData[r];
    32. } finally {
    33. // Preserve behavioral compatibility with AbstractCollection,
    34. // even if c.contains() throws.
    35. if (r != size) {
    36. System.arraycopy(elementData, r,
    37. elementData, w,
    38. size - r);
    39. w += size - r;
    40. }
    41. if (w != size) {
    42. // clear to let GC do its work
    43. for (int i = w; i < size; i++)
    44. elementData[i] = null;
    45. modCount += size - w;
    46. size = w;
    47. modified = true;
    48. }
    49. }
    50. return modified;
    51. }

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

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读