Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java LinkedList retainAll: duplicates survive membership filtering

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

LinkedList.retainAll removes each element absent from the supplied collection; it does not turn the list into a set.

Keep list multiplicity separate from membership

The allowed collection contains one receipt code and null. The source list holds that code twice. Both copies survive, the rejected code disappears, and null remains because the membership policy included it. If null is invalid in the domain, reject it before filtering rather than assuming retainAll cleans it.

Matching uses equality as implemented by the elements and the argument collection. Mutable keys, inconsistent equality or unexpectedly expensive membership checks can change both behavior and cost. For a stable policy, build a dedicated immutable set of allowed identifiers and decide whether order and duplicates matter.

Working program

Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class ReceiptRetentionPolicy {
    public static void main(String[] args) {
        LinkedList<String> receipts = new LinkedList<>(Arrays.asList("R-11", "R-12", "R-11", null));
        Set<String> allowed = new HashSet<>(Arrays.asList("R-11", null));
        System.out.println("changed=" + receipts.retainAll(allowed));
        System.out.println(receipts);
    }
}

Output

Output
changed=true
[R-11, R-11, null]

Costs and boundaries

A pass must inspect the n source elements; membership cost depends on the supplied collection's contains behavior. A hash-based allowed set normally reduces repeated lookup work, subject to correct hashCode and equals. The operation mutates the list; it is not an audit trail.

Common Mistakes

  • Do not assume retainAll deduplicates.
  • Do not let an allowed null silently bypass a domain rule.
  • Do not pass a slow membership collection into a large repeated filter without measuring.

Read next

Java LinkedList: operations, internals and failure cases, Java HashSet: deduplication and equality, Java equals and hashCode: stable value keys, Java LinkedList duplicate removal: first and last occurrence.

java
collections
linkedlist-retainall-equality
Storage details