In Java, removeIf(filter) goes through the LinkedList and removes every element for which the Predicate returns true. A predicate is a small test, usually written as a lambda such as n -> n < 0.
It replaces the old pattern of looping with an iterator and calling remove() yourself. It works in one pass and is safe, since the removal is done by the method and not by a loop over the same list.
An instance method of java.util.LinkedList (since Java 8): call it on a LinkedList object. Add import java.util.LinkedList; at the top of your file. It is declared by Collection, and LinkedList implements it. removeIf() was added in Java 8.
Syntax
Pass a lambda or a method reference that returns a boolean.
Java
LinkedList<Integer> nums = new LinkedList<>(Arrays.asList(5, -2, 8, -1));
boolean changed = nums.removeIf(n -> n < 0); // true
// nums is now [5, 8]
Call
What it does
list.removeIf(x -> test)
Removes every element where the test is true.
list.removeIf(Objects::isNull)
Removes all null elements.
list.removeAll(c)
Removes elements by membership in a collection.
list.iterator().remove()
The older way: remove while iterating by hand.
The test decides what is removed, not what is kept. Read x -> x < 0 as "remove x if x is less than 0".
Library declarations
Java
// java.util.LinkedList (default method from java.util.Collection)
public boolean removeIf(Predicate<? super E> filter)
Parameters
Parameter
Description
filter (Predicate<? super E>)
A test that returns true for the elements to remove. It must not be null.