Java ArrayList removeIf()

The syntax of the removeIf() method is:

arraylist.removeIf(Predicate<E> filter)

Here, arraylist is an object of the ArrayList class.


removeIf() Parameters

The removeIf() method takes a single parameter.

  • filter - decides whether an element is to be removed

removeIf() Return Value

  • returns true if an element is removed from the arraylist.

Example: Remove Even Numbers From ArrayList

Output

Numbers: [1, 2, 3, 4, 5, 6]
Odd Numbers: [1, 3, 5]

In the above example, we have created an arraylist named numbers. Notice the line,

numbers.removeIf(e -> (e % 2) == 0);

Here,

  • e -> (e % 2) == 0) is a lambda expression. It checks if an element is divided by 2. To learn more, visit Java Lambda Expression.
  • removeIf() - Remove the element if e -> (e % 2) == 0 returns true.

Example 2: Remove Countries With "land" in Name

Output

Countries: [Iceland, America, Ireland, Canada, Greenland]
Countries without land: [America, Canada]

In the above example, we have used the Java String contains() method to check if the element contains land in it. Here,

  • e -> e.contains("land") - returns true if the element contains land in it
  • removeIf() - removes the element if e -> e.contains("land") returns true.