How to Use ArrayList removeIf Method with Examples in Java2 min read

The removeIf() method is a method of the java.util.ArrayList class that allows you to remove all elements from an ArrayList that satisfy a given predicate (a boolean-valued function). It was introduced in Java 8 as a way to remove elements from a list using a declarative approach, rather than the imperative approach used by the remove() method.

Here is an example of how to use the removeIf() method:


In this example, the removeIf() method will remove the element “Alice” from the names list because it starts with the letter “A”. The resulting list will be [“Bob”, “Charlie”].

The removeIf() method takes a Predicate as an argument. A Predicate is a functional interface that represents a boolean-valued function of one argument. It specifies the condition that elements must meet to be removed from the collection. In the example above, the Predicate is a lambda expression that checks whether a name starts with the letter “A”.

You can also use the removeIf() method with a method reference or a traditional anonymous inner class instead of a lambda expression. Here is an example using a method reference.

Example: Removing elements from a list of strings that are empty or contain only whitespace:


This will remove all empty strings from the names list.

Example: Removing elements from a set of integers that are even:


After calling removeIf(), the numbers set will contain [1, 3].

Example: Removing elements from a map of strings to integers that have a value greater than 10:


After calling removeIf(), the values map will contain only the key-value pair (“Alice”, 5).

I hope these examples help clarify how to use the removeIf() method in Java! Let me know if you have any questions.

Leave a Comment