SoFunction
Updated on 2025-04-12

A very detailed explanation of Java retainAll method

Preface

In Java,retainAll()yesCollectionInterface (ListSetetc. set classes implement this interface) a method used to retain elements in the set that intersect with the specified set and delete all other elements.

The following is correctretainAll()Detailed explanation of the method.

1. Method definition

Method signature

boolean retainAll(Collection<?> c)

parameter

  • c: A collection that specifies the elements to be preserved.

Return value

  • Return onebooleanValue:
    • true: If the content of the collection changes due to calling this method.
    • false: If the content of the collection has not changed (i.e. the elements in the collection are the same before and after calling this method).

2. Function description

  • retainAll()The method will call the set of the method (assuming it isAAll elements and parameter sets in ) (assuming it isB) compare and retain the elements that intersect the two.
  • ifAThe element in it is not thereB, they will be removed.
  • Parameter setBWill not be modified.

3. Use examples

Basic usage

import ;
import ;

public class RetainAllExample {
    public static void main(String[] args) {
        ArrayList&lt;Integer&gt; list1 = new ArrayList&lt;&gt;((1, 2, 3, 4, 5));
        ArrayList&lt;Integer&gt; list2 = new ArrayList&lt;&gt;((3, 4, 5, 6, 7));

        // Keep the intersection of list1 and list2        (list2);

        (list1); // Output: [3, 4, 5]    }
}

Return value example

import ;
import ;

public class RetainAllExample {
    public static void main(String[] args) {
        ArrayList&lt;String&gt; list1 = new ArrayList&lt;&gt;(("A", "B", "C"));
        ArrayList&lt;String&gt; list2 = new ArrayList&lt;&gt;(("B", "C"));

        boolean isModified = (list2);

        (isModified); // Output: true, because list1 has changed        (list1); // Output: [B, C]    }
}

4. Common scenarios

Scene 1: Find the intersection of two sets

useretainAll()You can quickly find the intersection of two sets:

Set&lt;Integer&gt; set1 = new HashSet&lt;&gt;((1, 2, 3, 4));
Set&lt;Integer&gt; set2 = new HashSet&lt;&gt;((3, 4, 5, 6));

(set2);

(set1); // Output: [3, 4]

Scene 2: Remove unwanted elements from the collection

By comparing with a known set, the required elements are preserved and the rest are deleted:

List&lt;String&gt; fruits = new ArrayList&lt;&gt;(("Apple", "Banana", "Mango", "Orange"));
List&lt;String&gt; preferredFruits = ("Apple", "Orange");

(preferredFruits);

(fruits); // Output: [Apple, Orange]

5. Precautions and FAQs

Things to note

  • null collection not supported

    • If the parameter set isnull, callretainAll()Will be thrownNullPointerException
      List&lt;Integer&gt; list = new ArrayList&lt;&gt;((1, 2, 3));
      (null); // Throw NullPointerException
  • The original collection will be modified

    • After calling this method, the content of the original collection will be changed, leaving only the intersection elements.
  • Parameter set cannot be modified

    • retainAll()The parameter set will not be modified.

FAQ

  • Air intersection
    If the two sets have no intersection, thenretainAll()After that, the original collection will become empty.

    List&lt;Integer&gt; list1 = new ArrayList&lt;&gt;((1, 2, 3));
    List&lt;Integer&gt; list2 = new ArrayList&lt;&gt;((4, 5, 6));
    
    (list2);
    
    (list1); // Output: []
  • Retain in sequence
    If usedList(likeArrayList),retainAll()When the intersection is preserved, the order of elements is in the order of the original set.

    List&lt;Integer&gt; list1 = new ArrayList&lt;&gt;((1, 2, 3, 4));
    List&lt;Integer&gt; list2 = new ArrayList&lt;&gt;((4, 3));
    
    (list2);
    
    (list1); // Output: [3, 4]

6. Internal Principles

Execution process

  • Traversal callretainAll()A collection of  (such aslist1)。
  • For each element, check if it exists in the parameter set (e.g.list2)。
  • If it does not exist, remove the element.
  • returntrue, if at least one element is removed; otherwise returnfalse

efficiency

  • Depends on the type of parameter set:
    • If the parameter set is aHashSetretainAll()The performance is better becauseHashSetProvides a quick lookup operation (O(1)).
    • If the parameter set is aList, performance may be lower because the lookup operation requires linear time (O(n)).

7. Differences from other methods

removeAll()

  • the differenceremoveAll()is to delete elements in the current set that intersect with the specified set, andretainAll()It is the retained intersection element.
  • Example
    List&lt;Integer&gt; list1 = new ArrayList&lt;&gt;((1, 2, 3, 4));
    List&lt;Integer&gt; list2 = new ArrayList&lt;&gt;((3, 4, 5));
    
    // removeAll delete the intersection(list2);
    (list1); // Output: [1, 2]
    // retainAll retains intersectionlist1 = new ArrayList&lt;&gt;((1, 2, 3, 4));
    (list2);
    (list1); // Output: [3, 4]

8. Summary

method describe
effect Keep elements in the set that intersect with the specified set, and the remaining elements are deleted
Modify the original collection yes
Parameters cannot be empty If the parameter set is empty, it will be thrown.NullPointerException
Return value If the set changes, returntrue, otherwise returnfalse
Common uses Find intersections and filter elements in collections

retainAll()It is a common method for operating collections, which can help developers quickly perform intersection operations between collections. When using it, it is necessary to note that the original collection will be modified, so in some scenarios, the original collection data may need to be backed up to avoid data loss.

This is all about this article about the Java retainAll() method. For more related contents of the Java retainAll() method, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!