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().
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. |
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]
The return value of retainAll() indicates whether the target list was modified (not whether any elements matched):
[], so retainAll() returns true.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]
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]
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
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. |
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]
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]
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().
Calling list.retainAll(Collections.emptyList()) removes every element from list (since nothing is contained in an empty collection), leaving list completely empty.
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!
Use !Collections.disjoint(list1, list2), which returns true as soon as it finds the first shared element without mutating either list.
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.
Use Java 8+ list.removeIf(item -> !keepCondition(item)).
Yes. Surviving elements are compacted toward index 0 in their exact original sequence.
ArrayList.retainAll().ArrayList methods.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.