Codectionary / Developer documentation / Java

Removing Matching Items with removeIf

Remove collection elements using a predicate instead of modifying a list inside a for-each loop.

What it is and why to use it

Removing an item directly from a list while a for-each loop iterates it can invalidate the iterator. removeIf expresses the intended bulk operation: remove every element whose predicate is true. It changes the original collection and returns whether anything was removed.

How it works

The predicate below identifies scores lower than 50. A mutable ArrayList supports the operation. List.of supplies the initial values but is copied into the mutable list. A stream filter would instead create a processing pipeline and leave this list unchanged unless additional code mutated it.

Common mistakes and limitations

Do not expect removeIf to work on an unmodifiable list. Do not modify the same collection from inside the predicate. If a predicate throws, do not assume all collection implementations guarantee an all-or-nothing update.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

boolean changed = scores.removeIf(score -> score < 50);

Examples

Removing Matching Items with removeIf

Complete Main.java example — Java 17 or later, without preview features.

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> scores = new ArrayList<>(List.of(40, 72, 49, 90));
    boolean changed = scores.removeIf(score -> score < 50);
    System.out.println(scores);
    System.out.println(changed);
  }
}
  1. The source contains four scores in encounter order.
  2. The predicate is true for 40 and 49, so those elements are removed; 72 and 90 remain in their original order.
  3. changed is true because at least one removal occurred. This is useful for editing an in-memory working list after validation.
  4. Expected output: [72, 90] true

Best practices

  • Use a mutable collection when mutation is intended.
  • Use filtering into a new result when the source must be preserved.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading