In Java 8 and later, removeIf(filter) removes every element of an ArrayList for which the filter returns true. The filter is a Predicate<E>, usually written as a lambda such as n -> n < 0.
It is the safe, one-line replacement for removing elements inside a loop. The remaining elements keep their order, and the method returns true if at least one element was removed.
An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe. removeIf has been available since Java 8 as a default method of Collection; ArrayList overrides it with the same behavior.
Syntax
Pass a condition; matching elements are removed.
Java
List<Integer> list = new ArrayList<>(Arrays.asList(5, -2, 8, -1));
boolean any = list.removeIf(n -> n < 0); // true, list = [5, 8]
list.removeIf(n -> n > 100); // false, unchanged
Call
What it does
list.removeIf(x -> cond)
Removes all elements where cond is true.
list.removeIf(String::isEmpty)
Method reference: removes empty strings.
list.removeIf(Objects::isNull)
Removes all null elements.
list.removeIf(x -> true)
Removes everything (same result as clear()).
ArrayList's implementation tests the predicate on the elements first and then removes all matches in a single pass, so it avoids the index-shifting mistakes of a hand-written loop.
Library declarations
Java
// java.util.ArrayList<E>
public boolean removeIf(Predicate<? super E> filter)
// Declared in Collection<E> (default method since Java 8)
// java.util.function.Predicate<T>
boolean test(T t)
Parameters
Parameter
Description
filter (Predicate<? super E>)
Returns true for elements to remove. Must not be null.