.removeIf()

Anonymous contributor's avatar
Anonymous contributor
Published Mar 12, 2024
Contribute to Docs

The .removeIf() method removes all the elements of an ArrayList that satisfy a given predicate. Any error or runtime exception thrown during the iteration or by the predicate is relayed to the caller. If any element is removed, this method returns true. Otherwise, it returns false.

Syntax

arrayListInstance.removeIf(Predicate<T> filter);
  • arrayListInstance: The name of the ArrayList to be checked.
  • Predicate<T>: A functional interface representing a condition that takes a single argument of type T.
  • filter: The condition that needs to be checked.

Example

In the following example, the .removeIf() method removes all the even elements from an ArrayList called nums:

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(10);
nums.add(15);
nums.add(20);
nums.add(30);
nums.removeIf(n -> (n % 2 == 0));
System.out.println(nums);
}
}

Here is the output for the above example:

[15]

All contributors

Contribute to Docs

Learn Java on Codecademy