ArrayList.removeIf(Predicate) in Java

ArrayList.removeIf(Predicate<? super E>): This method is available in java.util.ArrayList class of Java.

Syntax:

boolean java.util.ArrayList.removeIf(Predicate<? super Integer> filter)

This method takes one argument. This method removes all of the elements of this collection that satisfy the given predicate.

Parameters: One parameter is required for this method.

filter: a predicate which returns true for elements to beremoved.

Returns: true if any elements were removed.

Throws:

NullPointerException - if the specified filter is null

Approach 1: When no exception

Java

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListRemoveIf {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);

        System.out.println("Before remove : " +
Arrays.asList(arr));
        arr.removeIf(x -> x % 2 == 0);
        System.out.println("After remove : " +
Arrays.asList(arr));

    }
}

Output:

Before remove : [[1, 2, 3]]

After remove : [[1, 3]]

Approach 2: NullPointerException

Java

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListRemoveIf {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);

        System.out.println("Before remove : " +
Arrays.asList(arr));
        arr.removeIf(null);
        System.out.println("After remove : " +
Arrays.asList(arr));

    }
}

Output:

Before remove : [[1, 2, 3]] Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.ArrayList.removeIf(ArrayList.java:1668) at java.base/java.util.ArrayList.removeIf(ArrayList.java:1660)


No comments:

Post a Comment