RemoveIf Predicate Based Removal

RemoveIf deletes every element matching a predicate in one pass and reports whether anything changed, unlike manual iterator removal loops.

JavaData Integrity

Code

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

public class RemoveIfPredicateRemoval {

    record Task(String name, boolean done) {}

    public static void main(String[] args) {
        List<Task> tasks = new ArrayList<>(List.of(
                new Task("build", true),
                new Task("test", false),
                new Task("release", false),
                new Task("cleanup", true)));

        // removeIf:谓词一次删除全部匹配项,返回是否发生变更
        boolean changed = tasks.removeIf(Task::done);
        System.out.println("changed = " + changed);
        System.out.println("remaining = " + tasks);

        // 换一个条件继续删
        tasks.removeIf(task -> task.name().startsWith("re"));
        System.out.println("after second = " + tasks);

        // 不可变集合上调用会抛 UnsupportedOperationException
        try {
            List.of(1, 2, 3).removeIf(n -> n == 2);
        } catch (UnsupportedOperationException e) {
            System.out.println("immutable list rejected: " + e.getClass().getSimpleName());
        }
    }
}

How it works

RemoveIf Predicate Based Removal comes down to the classes RemoveIfPredicateRemoval and Task and the function main.

Points of care

  • What the toolchain ships is enough — nothing further is needed.

Putting it to use

Entry signature: public static void main(String[] args)

The output walks through each step by label: changed =, remaining =, after second =.

Core lines

tasks.removeIf(task -> task.name().startsWith("re"));
boolean changed = tasks.removeIf(Task::done);
List.of(1, 2, 3).removeIf(n -> n == 2);

Interactive Tools for This Topic

FAQ

What does RemoveIf Predicate Based Removal print when run?
Invoke the file as-is — the `changed =`, `remaining =`, `after second =` prefixes identify which step printed each line.