Java List.removeIf
Remove every element satisfying a predicate from a mutable list and report whether anything changed.
A simple example
List.removeIf
- Start with 1, 2, 3
- Do this Remove values below 2
- Result 2, 3
Syntax
stock.removeIf(quantity -> quantity == 0)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaClear empty stock bins from the pick list
A stockroom prints only bins that contain items a picker can collect. Empty bins appear twice in today's count, and both should disappear while the remaining quantities keep their order.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var counts = new ArrayList<>(List.of(4, 0, 2, 0));
counts.removeIf(n -> n == 0);
System.out.println(counts.get(0) + ", " + counts.get(1));
}
}
4, 2
Removing every zero leaves the two positive counts in their original order.
See whether an attendance list changed
A receptionist cleans a list of confirmed attendees before sending it to a printer. She can avoid reprinting the badges if there are no blank names to remove.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var names = new ArrayList<>(List.of("Mira", "Sam"));
System.out.println(names.removeIf(String::isBlank));
}
}
false
Both names contain visible text, so removeIf reports that the list did not change.
Keep only the badges on today's guest list
A receptionist brings reusable badges left over from yesterday's workshop. She checks today's guest list and keeps the matching badges, in their original tray order, for people returning this morning.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var badges = new ArrayList<>(List.of("Mira", "Lee", "Sam"));
badges.retainAll(List.of("Sam", "Mira"));
System.out.println(String.join(", ", badges));
}
}
Mira, Sam
retainAll keeps every matching entry in its original order, even though Sam appears first on the guest list.
Take recalled products off the shelf list
A shop receives a recall covering two product names. The inventory clerk removes every occurrence of those names from the shelf list, including a second box of the same product.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var shelf = new ArrayList<>(List.of("Mug", "Tea", "Mug", "Cup"));
shelf.removeAll(List.of("Mug", "Cup"));
System.out.println(String.join(", ", shelf));
}
}
Tea
removeAll removes all three matching entries. Tea remains on the shelf list.
What to watch for
Implementations can reject removal. Use a filtered copy when the original list must be retained.