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

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();

        // add elements to the ArrayList
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        numbers.add(6);
        System.out.println("Numbers: " + numbers);

        // remove all even numbers
        numbers.removeIf(e -> (e % 2) == 0);;
        System.out.println("Odd Numbers: " + numbers);
    }
}

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

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<String> countries = new ArrayList<>();

        // add elements to the ArrayList
        countries.add("Iceland");
        countries.add("America");
        countries.add("Ireland");
        countries.add("Canada");
        countries.add("Greenland");
        System.out.println("Countries: " + countries);

        // remove all even countries
        countries.removeIf(e -> e.contains("land"));;
        System.out.println("Countries without land: " + countries);
    }
}

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.

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges