ArrayList.removeAll(Collection) in Java

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

Syntax:

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

This method removes from this list all of the elements that are contained in the specified collection.

Parameters: One parameter is required for this method.

c: a collection containing elements to be removed from 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 incompatible 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

Java

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

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

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

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

    }
}

Output:

Before remove : [[1, 5]]

After remove : [[5]]


No comments:

Post a Comment