ArrayList removeIf() Method in Java with Examples (original) (raw)

Last Updated : 11 Dec, 2024

The Java ArrayList **removeIf() method is used to remove all elements from the ArrayList that satisfy a given **predicate filter. The predicate is passed as a parameter to the method, and any runtime exceptions thrown during iteration or by the predicate are passed to the caller.

The removeIf() method uses Java 8’s Predicate functional interface to apply conditions for removing elements.

**Example 1: Here, we use the **removeIf() method **to remove numbers divisible by 3 from an ArrayList of integers.

Java `

// Java program to demonstrate the use of removeIf() // method with ArrayList of Integers import java.util.ArrayList;

public class GFG { public static void main(String[] args) {

    // create an ArrayList of integers
    ArrayList<Integer> num = new ArrayList<>();

    // Adding numbers to 
    // the ArrayList
    num.add(23);
    num.add(32);
    num.add(45);
    num.add(63);

    // Using removeIf() method to remove 
    // numbers divisible by 3
    num.removeIf(n -> (n % 3 == 0));

    System.out.println(num);
}

}

`

Syntax of ArrayList removeIf() Method

boolean removeIf(Predicate filter)

Other Examples of Java ArrayList removeIf() Method

**Example 2: Here, we use the **removeIf() method **to remove names starting with the letter ‘S’ from an ArrayList of **strings.

Java `

// Java program to demonstrate the use of removeIf() // method with ArrayList of Strings import java.util.ArrayList;

public class GFG { public static void main(String[] args) {

    // Creating an ArrayList of student names
    ArrayList<String> s = new ArrayList<>();

    // Adding student names to the ArrayList
    s.add("Sweta");
    s.add("Gudly");
    s.add("Sohan");
    s.add("Amiya");
    s.add("Ram");

    // Using removeIf() method to 
    // remove names starting with 'S'
    s.removeIf(name -> name.startsWith("S"));

    System.out.println("Students whose names do not start with S:");
    System.out.println(s);
}

}

`

Output

Students whose names do not start with S: [Gudly, Amiya, Ram]