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

Java LinkedList removeIf: keep a predicate narrow and side-effect free

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

LinkedList.removeIf removes every element for which a predicate returns true while preserving the order of survivors.

Define the removal rule before mutating

A retry queue holds expired and live receipts. The predicate removes only IDs with the expired prefix. The remaining entries retain their relative order, and the returned boolean reports whether anything changed.

The predicate sees each element during traversal. Do not mutate the same list from inside it or depend on a partially processed list after the predicate throws. If rejection must leave the original untouched, validate first or build a new list and publish it only after success. Cursor edits are a separate explicit mutation path.

Keep the domain rule separate

Prefix matching is only a fixture. A real expiry rule needs a clock and a parsed deadline; injecting time avoids inconsistent tests. A List is also a poor choice when the primary operation is repeatedly finding one receipt by ID.

Working program

Java
import java.util.Arrays;
import java.util.LinkedList;
public class ExpiredReceiptCleanup {
    public static void main(String[] args) {
        LinkedList<String> pending = new LinkedList<>(Arrays.asList(
            "live:R-41", "expired:R-39", "live:R-42", "expired:R-40"));
        boolean changed = pending.removeIf(id -> id.startsWith("expired:"));
        System.out.println("changed=" + changed);
        System.out.println(pending);
    }
}

Output

Output
changed=true
[live:R-41, live:R-42]

Costs and boundaries

A full removal pass inspects n elements and needs no separate survivor list in this fixture. Predicate work adds to that cost. Do not claim transaction semantics or a rollback guarantee for predicate failure.

Common Mistakes

  • Do not mutate the backing list from inside its predicate.
  • Do not treat a throwing predicate as an all-or-nothing operation.
  • Do not encode production expiry as a string prefix.

Read next

Java LinkedList: operations, internals and failure cases, Java LinkedList ListIterator: edit at a cursor without repeated searches, Java Clock: test expiry without sleeping.

java
collections
linkedlist-removeif-policy
Storage details