Collection.removeIf()
Removes all collection elements that match a condition.
Available since: Java 8
Syntax
default boolean removeIf(Predicate<? super E> filter)Parameters
| Parameter | Type | Description |
|---|---|---|
| filter | Predicate<? super E> | A condition: elements for which it is true are removed. |
Return value
boolean`true` if anything was removed.
Examples
Removing blank strings:
void main() {
List<String> lines = new ArrayList<>(List.of("one", "", "two", " ", "three"));
lines.removeIf(String::isBlank);
IO.println(lines);
}Output:
[one, two, three]It works for sets and for map values too:
void main() {
Set<Integer> nums = new TreeSet<>(List.of(1, 2, 3, 4, 5));
nums.removeIf(n -> n > 3);
IO.println(nums);
Map<String, Integer> stock = new TreeMap<>(Map.of("pen", 0, "cup", 4));
stock.values().removeIf(q -> q == 0);
IO.println(stock);
}Output:
[1, 2, 3]
{cup=4}Notes
It changes the collection itself, unlike stream().filter(), which creates a new one. The condition says what to remove, while filter() says what to keep — do not mix up the sign.
See also
- Iterator — An object that hands out collection elements one by one.
- List.remove() — Removes a list element by index or by value.
- Stream.filter() — Keeps only the stream elements that match a condition.
- Predicate — A condition: a function that takes a value and returns a `boolean`.
Related recipes
In the tutorial
- Iterating over collections — How to go through a collection in Java: the for-each loop, indexes, forEach with a lambda, iterating a map, Iterator and removeIf.