Java ArrayList removeIf() Method

Java ArrayList Java ArrayList

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

The syntax of the removeIf() method is:

arraylist.removeIf(Predicate<E> filter)

Note:arraylist is an object of the ArrayList class.

Parameter Description:

  • filter - A filter that determines whether an element should be removed.

Return Value

Returns true if an element is 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 a dynamic array
        ArrayList<String> sites = new ArrayList<>();
       
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");

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

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

The output of the above program is:

ArrayList : [Google, Example, Taobao]
删除后的 ArrayList: [Google, Example]

In the above example, we usedJava String contains() methodto check whether the element contains "Tao".

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

removeIf()Ife -> e.contains("land")returns true, the element is removed.

Remove even elements:

Example

import java.util.ArrayList;

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

        // Insert elements into the array
        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);
    }
}

The output of the above program is:

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

In the above example, we created a dynamic array named numbers.

Note the expression:

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

e -> (e % 2) == 0)is a lambda expression (anonymous function). It checks whether an element is divisible by 2.

To learn more about anonymous functions, visitJava Lambda Expressions。

removeIf()If the methode -> (e % 2) == 0returns true, then the element is removed.

Java ArrayList Java ArrayList

Other Extensions