liveBook · Manning

removeIf method

As explained in 100 Java Mistakes and How to Avoid Them

The removeIf method removes elements from a collection that satisfy a supplied predicate.

The removeIf method removes collection elements whose supplied predicate returns true. Use it when the removal condition does not depend on an element’s index. Keep the predicate from modifying the same collection, because implementations commonly detect that pattern and throw ConcurrentModificationException. section 8.10 section 8.11

A predicate that reads the collection

A predicate such as c.removeIf(x -> c.contains(x - 1)) can produce different results for equivalent collection contents. ArrayList evaluates predicates before applying removals, while TreeSet may remove elements as it iterates; therefore the predicate can observe either the original or partially modified collection. section 8.11

data.removeIf(this::condition);

Shows the compact method-reference form for predicate-based removal. section 8.10

Choose the removal technique according to the condition:

  • Use removeIf when the predicate depends only on the element and stable external state. section 8.10
  • Use an Iterator when removal accompanies more complex processing; its remove operation does not skip the next element. section 8.10
  • Use subList(...).clear() for an unconditional range removal, with a bounds check. section 8.10

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains predicate removal and implementation-dependent collection visibility, but does not develop broader collection internals.
Examples
Uses method references, adjacent-number sequences, and ArrayList, TreeSet, and ArrayDeque comparisons.
What it assumes
Assumes familiarity with Java collections, predicates, iteration, and indexed list traversal.
What you can do after
Apply it via Collection.removeIf while keeping predicates independent of collection mutation and unstable collection state.
How it connects
Connects predicates with iterators, indexed removal, ArrayList, TreeSet, ArrayDeque, and ConcurrentModificationException.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.