SoFunction
Updated on 2025-05-21

Java finds multiple implementations of intersection elements of two List collections

1. Use the retainAll method

retainAllyesCollectionA method in the interface that preserves the same elements in the set as the specified set and removes other elements.

principle:

  • retainAllThe method will iterate over the current collection and check whether each element exists in the specified collection.
  • If the element does not exist in the specified collection, the element is removed from the current collection.
  • Ultimately, the current collection only retains the same elements as the specified collection.

retainAllIt's in JavaListAn method provided by the interface is used to retain the same elements in the list as in the specified collection and remove all other elements. in other words,retainAllThe method will modify the current list so that it only contains the same elements as in the specified collection.

Method definition

boolean retainAll(Collection<?> c);

parameter:

  • c: Contains a collection that needs to be preserved.

Return value:

  • If the list changes due to calling this method, returntrue
  • If the list has not changed (i.e. the list already contains only elements in the specified collection), then returnfalse

Method behavior

  • Keep intersectionretainAllThe method retains the intersection of the current list and the specified set.
  • Remove other elements: Elements in the current list that are not in the specified collection will be removed.
  • Modify the original listretainAllThe method will directly modify the current list, rather than returning a new list.

Sample code

Here is a simple example showingretainAllMethod usage:

import ;
import ;

public class RetainAllExample {
    public static void main(String[] args) {
        // Create two lists        List&lt;String&gt; list1 = new ArrayList&lt;&gt;();
        ("Apple");
        ("Banana");
        ("Cherry");
        ("Date");

        List&lt;String&gt; list2 = new ArrayList&lt;&gt;();
        ("Banana");
        ("Date");
        ("Fig");

        // Call the retainAll method        boolean isChanged = (list2);

        // Output result        ("Did List1 change: " + isChanged); // true
        ("List1's content: " + list1); // [Banana, Date]
        ("List2's content: " + list2); // [Banana, Date, Fig]
    }
}

Output:

List1 Have there been any changes: true
List1 Contents: [Banana, Date]
List2 Contents: [Banana, Date, Fig]

Key points

  1. Modify the original list

    • retainAllThe method will directly modify the list that calls it, rather than returning a new list.
    • If you need to keep the original list, you can call itretainAllCreate a copy before.
  2. Return value

    • If the list is calledretainAllIf a change occurs, returntrue
    • If the list has not changed (i.e. the list already contains only elements in the specified collection), then returnfalse
  3. Collection comparison

    • retainAllMethods depend onequalsMethod to compare whether the elements are the same.
    • If the collection contains custom objects, make sure it has been rewrited correctly.equalsandhashCodemethod.
  4. Empty collection

    • If the incoming collection is empty (nullor empty set),retainAllWill be thrownNullPointerExceptionOr clear the current list.

Things to note

  1. Performance issues

    • retainAllThe time complexity of the method depends on the implementation of the list. ForArrayList, the time complexity is O(n*m), where n is the size of the list and m is the size of the set.
    • If both lists and collections are large, performance may be affected.
  2. Collection Type

    • retainAllThe method can accept any implementationCollectionThe object of the interface is used as a parameter, for exampleListSetwait.
  3. Repeat elements

    • If there are duplicate elements in the list and there are no duplicate elements in the specified collection,retainAllRepeated elements in the list will be retained.
    • For example:
List&lt;String&gt; list1 = new ArrayList&lt;&gt;(("A", "A", "B", "C"));
List&lt;String&gt; list2 = new ArrayList&lt;&gt;(("A", "B"));
(list2);
(list1); // Output [A, A, B]

Note:

  • retainAllMethods are used to retain the same elements in the list as in the specified collection and remove other elements.
  • It directly modifies the original list and returns a boolean value indicating whether the list has changed.
  • When using it, you need to pay attention to performance issues and compatibility of collection types.
  • If you need to keep the original list, you can call itretainAllCreate a copy before.

2. Use the Stream API

Java 8 has introducedStreamAPI, which can easily operate on collections.

principle:

  • usestream()The method willListConvert to stream.
  • usefilterMethod filters out elements that exist in another collection.
  • usecollectMethod collects the results into a newListmiddle.

Sample code:

import ;
import ;
import ;

public class Main {
    public static void main(String[] args) {
        List&lt;Integer&gt; list1 = new ArrayList&lt;&gt;();
        (1);
        (2);
        (3);

        List&lt;Integer&gt; list2 = new ArrayList&lt;&gt;();
        (2);
        (3);
        (4);

        List&lt;Integer&gt; intersection = ()
                .filter(list2::contains)
                .collect(());

        (intersection); // Output: [2, 3]    }
}

3. Manual traversal

Manually traverse twoListand find common elements.

principle:

  • Traversing the first oneListEach element in it.
  • Check if this element exists in the secondListmiddle.
  • If present, add it to the result set.

Sample code:

import ;
import ;

public class Main {
    public static void main(String[] args) {
        List&lt;Integer&gt; list1 = new ArrayList&lt;&gt;();
        (1);
        (2);
        (3);

        List&lt;Integer&gt; list2 = new ArrayList&lt;&gt;();
        (2);
        (3);
        (4);

        List&lt;Integer&gt; intersection = new ArrayList&lt;&gt;();
        for (Integer item : list1) {
            if ((item)) {
                (item);
            }
        }

        (intersection); // Output: [2, 3]    }
}

Summarize

  • retainAllThe method is the most direct way, but it will modify the original collection.
  • StreamThe API provides a more flexible and functional programming method without modifying the original collection.
  • Manual traversal is suitable for scenarios where custom logic is required, but the amount of code is large.

Just choose the appropriate method according to the specific needs.

This is the article about Java's multiple implementations of intersection elements of two List collections. For more related contents of two List collections, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!