Java Utility Library

Java ArrayList - removeIf() Method



The java.util.ArrayList.removeIf() method is used to remove all of the elements of the list that satisfy the given predicate.

Syntax

public boolean removeIf(Predicate<? super E> filter)

Here, E is the type of element maintained by the container.


Parameters

filter Specify filter, a predicate which returns true for elements to be removed.

Return Value

Returns true if any elements were removed.

Exception

Throws NullPointerException, if the specified filter is null.

Example:

In the example below, the java.util.ArrayList.removeIf() method is used to remove all of the elements of the list which are divisible by 10.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating the ArrayList
    MyList.add(5);
    MyList.add(10);
    MyList.add(15);
    MyList.add(20);
    MyList.add(25);
    MyList.add(30);

    //printing MyList
    System.out.println("Before removeIf, MyList contains: " + MyList);

    //remove all elements which are divisible by 10
    MyList.removeIf((n) -> (n % 10 == 0));

    //printing MyList
    System.out.println("After removeIf, MyList contains: " + MyList);
  }
}

The output of the above code will be:

Before removeIf, MyList contains: [5, 10, 15, 20, 25, 30]
After removeIf, MyList contains: [5, 15, 25]

❮ Java.util - ArrayList