Skip to content
Tutorials Center
My learning

Topics

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.

Java
list.removeIf(s -> s.isBlank());
list.replaceAll(String::trim);

Try it

Java Filtering and transforming in place

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.

Java Why not remove inside a for-each loop

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

Java
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)); repeated remove(i) calls cost O(n^2).
  • removeIf works on the live collection; to keep the original use a stream: list.stream().filter(...).toList().
  • replaceAll keeps 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 support replaceAll (and write through to the array) but not removeIf when it would remove something.
  • Maps: map.values().removeIf(...), map.keySet().removeIf(...) and map.entrySet().removeIf(...) remove entries; Map.replaceAll(BiFunction) updates values.
  • Order of calls: the predicate/operator is applied in iteration order for lists.