Java ArrayList.retainAll(): List Intersection & Filtering Common Elements

The ArrayList.retainAll(Collection<?> c) method retains only the elements in the target list that are also contained in the specified collection c, removing all non-matching elements in a single pass.

Set Intersection Counterpart: retainAll() is the exact complement of ArrayList.removeAll(): whereas removeAll(c) deletes elements present in c, retainAll(c) keeps only elements present in c. To copy a list before computing an intersection, use new ArrayList<>(list) or ArrayList.clone().

1. Syntax, Method Signature & Two-Pointer Compaction 🔝

Declared in java.util.ArrayList<E>:

 // Retains only the elements in this list that are contained in the specified collection c
public boolean retainAll(Collection<?> c)
Element Type / Complexity Operational Rule
c Collection<?> Collection of elements to keep in this list (must not be null).
Return Value boolean true if at least 1 non-matching element was removed; false if the list did not change.
Time Complexity O(n * m) or O(n) Tests c.contains(e) for each item; O(n) when c is a HashSet.

2. Basic List Intersection with retainAll() 🔝

Calling languages.retainAll(front_end) keeps only "HTML" and "PhotoShop" (the elements common to both lists) and removes "Java", "PHP", and "Python". Because 3 elements were removed from languages, the method returns true inside the if-else check:

ArrayList<String> languages = new ArrayList<>(
    Arrays.asList("Java", "PHP", "HTML", "Python", "PhotoShop")
);
System.out.println(languages);

ArrayList<String> front_end = new ArrayList<>(
    Arrays.asList("HTML", "PhotoShop", "JavaScript")
);

if (languages.retainAll(front_end)) {
    System.out.println("Retained matching elements only (non-matches removed)");
}
System.out.println(languages);

Terminal Output:

[Java, PHP, HTML, Python, PhotoShop]
Retained matching elements only (non-matches removed)
[HTML, PhotoShop]

3. Understanding the boolean Return Value (Disjoint vs Subset) 🔝

The return value of retainAll() indicates whether the target list was modified (not whether any elements matched):

  • Disjoint lists (zero matches): All elements are removed, leaving [], so retainAll() returns true.
  • Subset list (all elements match): Zero elements are removed, leaving the list unchanged, so retainAll() returns false.
ArrayList<String> listA = new ArrayList<>(Arrays.asList("Java", "PHP"));
System.out.println("Disjoint changed? " + listA.retainAll(Arrays.asList("HTML2")) + " | " + listA);

ArrayList<String> listB = new ArrayList<>(Arrays.asList("Java", "PHP"));
System.out.println("Subset changed?   " + listB.retainAll(Arrays.asList("Java", "PHP", "Python")) + " | " + listB);

Terminal Output:

Disjoint changed? true | []
Subset changed?   false | [Java, PHP]

4. How retainAll() Handles Duplicate Elements 🔝

If an element appears multiple times in the main ArrayList and is present at least once in front_end, every occurrence in the main list is retained in its original order:

ArrayList<String> languages = new ArrayList<>(
    Arrays.asList("Java", "PHP", "HTML", "Python", "HTML", "PhotoShop")
);
languages.retainAll(Arrays.asList("HTML", "PhotoShop", "JavaScript"));
System.out.println("Retained with duplicates: " + languages);

Terminal Output:

Retained with duplicates: [HTML, HTML, PhotoShop]

5. HashSet O(n) Optimization & NullPointerException Rule 🔝

When intersecting large lists, wrap the argument collection in new HashSet<>(c) so membership checks run in O(1) instead of O(m). Never pass a null collection reference, which throws a NullPointerException:

ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(10, 20, 30, 40));
nums.retainAll(new HashSet<>(Arrays.asList(20, 40, 60)));
System.out.println("Retained via HashSet: " + nums);

try {
    nums.retainAll(null);  // Passing null throws NullPointerException!
} catch (NullPointerException ex) {
    System.out.println("Caught retainAll(null): NullPointerException");
}

Terminal Output:

Retained via HashSet: [20, 40]
Caught retainAll(null): NullPointerException

6. Comparison: Set Operations on Java ArrayList 🔝

How to express standard mathematical set operations using ArrayList methods:

Set Operation ArrayList Method Effect on Target List A
Intersection A.retainAll(B) Keeps only elements present in both A and B.
Difference A.removeAll(B) Keeps elements in A that are not in B.
Union (with dups) A.addAll(B) Appends all elements of B onto A.
Subset Test A.containsAll(B) Read-only check; returns true if every item of B is in A.

7. Production Recipe: Non-Destructive List Intersection 🔝

Cloning the first list via new ArrayList<>(a) before calling retainAll() computes the shared elements without mutating either input list:

public class NonDestructiveIntersection {
    public static <E> ArrayList<E> intersect(List<E> a, Collection<?> b) {
        ArrayList<E> res = new ArrayList<>(a);
        res.retainAll(new HashSet<>(b));
        return res;
    }
    public static void main(String[] args) {
        System.out.println("Shared: " + intersect(Arrays.asList("READ", "WRITE"), Arrays.asList("WRITE", "EXPORT")));
    }
}

Terminal Output:

Shared: [WRITE]

8. Practical Recipe: Finding Common Elements Across 3+ Lists 🔝

Chaining retainAll() across multiple candidate lists narrows the result down to elements present in every list:

public class MultiListIntersection {
    public static void main(String[] args) {
        ArrayList<String> common = new ArrayList<>(Arrays.asList("Java", "SQL", "Docker", "Git"));
        common.retainAll(Arrays.asList("Java", "Python", "SQL", "Git"));
        common.retainAll(Arrays.asList("Go", "SQL", "Git"));
        System.out.println("Skills in all 3 lists: " + common);
    }
}

Terminal Output:

Skills in all 3 lists: [SQL, Git]

9. Common Developer Pitfalls & Traps 🔝

Misinterpreting if (list.retainAll(filter)) as "If Matches Found"

list.retainAll(filter) returns true even when zero elements match (because removing all elements modified the list), and returns false when every element matched! To check whether any common elements survived after calling list.retainAll(filter), check !list.isEmpty().

Passing an Empty Collection Wipes the Target List

Calling list.retainAll(Collections.emptyList()) removes every element from list (since nothing is contained in an empty collection), leaving list completely empty.

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListRetainAllFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "B"));
        if (list.retainAll(Arrays.asList("B", "D")) && list.equals(Arrays.asList("B", "B"))) {
            System.out.println("Check 1 Passed: Retained both 'B' elements.");
        }
        if (!list.retainAll(Arrays.asList("B", "Z"))) {
            System.out.println("Check 2 Passed: Unchanged list returned false.");
        }
        System.out.println("All ArrayList.retainAll() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: Retained both 'B' elements.
Check 2 Passed: Unchanged list returned false.
All ArrayList.retainAll() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

How can I check if two ArrayLists have at least one common element without modifying them?

Use !Collections.disjoint(list1, list2), which returns true as soon as it finds the first shared element without mutating either list.

Does list1.retainAll(list2) deduplicate the surviving elements?

No. If "HTML" appears twice in list1 and once in list2, both copies of "HTML" remain in list1. Wrap the result in a LinkedHashSet if you also want deduplication.

How do I retain only elements that match a boolean condition?

Use Java 8+ list.removeIf(item -> !keepCondition(item)).

Does retainAll() preserve the relative order of surviving elements?

Yes. Surviving elements are compacted toward index 0 in their exact original sequence.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer