Easy Tutorial
❮ String Reverse Java Array ❯

Java ArrayList removeIf() Method

Java ArrayList

The removeIf() method is used to remove all elements that satisfy a specific condition from the array.

The syntax for the removeIf() method is:

arraylist.removeIf(Predicate<E> filter)

Note: arraylist is an object of the ArrayList class.

Parameter Description:

Return Value

Returns true if elements are removed.

Example

The following example demonstrates the use of the removeIf() method:

Example

import java.util.*;

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

        // Create an ArrayList
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("tutorialpro");
        sites.add("Taobao");

        System.out.println("ArrayList : " + sites);

        // Remove elements containing "Tao"
        sites.removeIf(e -> e.contains("Tao"));
        System.out.println("ArrayList after removal: " + sites);
    }
}

Executing the above program outputs:

ArrayList : [Google, tutorialpro, Taobao]
ArrayList after removal: [Google, tutorialpro]

In the above example, we used the Java String contains() method to check if the element contains "Tao".

e -> e.contains("land") returns true if the element contains "land".

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

Removing elements that are even:

Example

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 elements
        numbers.removeIf(e -> (e % 2) == 0);
        System.out.println("Odd Numbers: " + numbers);
    }
}

Executing the above program outputs:

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

In the above example, we created an ArrayList named numbers.

Note the expression:

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

e -> (e % 2) == 0 is a lambda expression that checks if an element is divisible by 2.

To learn more about lambda expressions, visit Java Lambda Expressions.

The removeIf() method removes the element if e -> (e % 2) == 0 returns true.

Java ArrayList

❮ String Reverse Java Array ❯