Java Reference ยท Collections
Java removeIf() and replaceAll() methods
Reference for Java Collection.removeIf() and List.replaceAll(): bulk-remove or transform elements with lambdas, safe alternatives to loop removal, and edge cases.
removeIf(Predicate) deletes every element for which the predicate returns true, and replaceAll(UnaryOperator) replaces every element of a list with the result of a function. Both arrived in Java 8 and are the clean way to filter or transform a collection in place without writing an iterator loop.
removeIf() belongs to Collection, so it works on lists, sets and queues. It returns true if anything was removed. replaceAll() belongs to List (maps have their own replaceAll(BiFunction)). Neither creates a new collection, so they fail on immutable ones.
list.removeIf(s -> s.isBlank()); list.replaceAll(String::trim);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
default boolean removeIf(Predicate<? super E> filter) // Collection default void replaceAll(UnaryOperator<E> operator) // List
| Name | Description |
|---|---|
filter |
Returns true for elements to remove. |
operator |
Takes an element and returns its replacement (same type E). |
Returns: removeIf returns true if at least one element was removed; replaceAll returns nothing.
Throws: NullPointerException if the function is null; UnsupportedOperationException when the collection cannot be modified (for removeIf on List.of() it can be thrown even if nothing would match); an exception thrown by your lambda propagates.
Usage notes
- Efficient:
ArrayList.removeIf()compacts the array in one pass (O(n)); repeatedremove(i)calls costO(n^2). removeIfworks on the live collection; to keep the original use a stream:list.stream().filter(...).toList().replaceAllkeeps the type. To change element types, map into a new list with a stream.- Keep lambdas pure: avoid changing the same collection inside them.
Arrays.asList()lists supportreplaceAll(and write through to the array) but notremoveIfwhen it would remove something.- Maps:
map.values().removeIf(...),map.keySet().removeIf(...)andmap.entrySet().removeIf(...)remove entries;Map.replaceAll(BiFunction)updates values. - Order of calls: the predicate/operator is applied in iteration order for lists.
Related
- Collection, List.add() and remove(), Iterator, List.sort()
- Lessons: Iterators, Lambdas