ArrayList.retainAll(Collection) in Java

ArrayList.retainAll(Collection<?>): This method is available in java.util.ArrayList class of Java.

Syntax:

boolean java.util.ArrayList.retainAll(Collection<?> c)

This method takes one argument. This method retains only the elements in this list that are contained in the specified collection. In other words, removes from this list all of its elements that are not contained in the specified collection.

Parameters: One parameter is required for this method.

c: collection containing elements to be retained in this list.

Returns: true if this list changed as a result of the call.

Throws:

1. ClassCastException - if the class of an element of this list is in compatible with the specified collection.

2. NullPointerException - if this list contains a null element and the specified collection does not permit null elements or if the specified collection is null.

Approach 1: When no excpetion

Java

import java.util.ArrayList;

public class ArrayListretainAll {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();

        arr.add(1);
        arr.add(2);
        arr.add(3);
        ArrayList<Integer> arr1 = new ArrayList<>();

        arr1.add(1);
        arr1.add(3);
        arr.retainAll(arr1);

        arr.forEach((n -> System.out.print(n + " ")));

    }
}

Output:

1 3 

Approach 2: NullPointerException

Java

import java.util.ArrayList;

public class ArrayListretainAll {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();

        arr.add(1);
        arr.add(2);
        arr.add(3);
        ArrayList<Integer> arr1 = null;
        arr.retainAll(arr1);

        arr.forEach((n -> System.out.print(n + " ")));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.ArrayList.batchRemove(ArrayList.java:816) at java.base/java.util.ArrayList.retainAll(ArrayList.java:811)


No comments:

Post a Comment