ArrayList removeAll() Method in Java

Published by user on

ArrayList removeAll() is used to remove all the elements contained in the specified collection from the list. It throws NullPointerException if the specified collection is null.

Syntax:

public boolean removeAll(Collection c)

Parameter – c is the collection of elements to be removed from the list.
Returns – true if the list changed as a result of this call.
Throws – NullPointerException if the specified collection is null.

ArrayList removeAll() Example

import java.util.ArrayList;

public class ArrayListRemoveAllExample {

	public static void main(String[] args) {
		ArrayList<Integer> numbers = new ArrayList<>();
		numbers.add(11);
		numbers.add(17);
		numbers.add(32);
		numbers.add(25);
		numbers.add(80);
		numbers.add(44);

		ArrayList<Integer> oddNumbers = new ArrayList<>();
		oddNumbers.add(11);
		oddNumbers.add(17);
		oddNumbers.add(25);

		System.out.println("ArrayList element: " + numbers);

		numbers.removeAll(oddNumbers);
		System.out.println("ArrayList after removing all elements of oddNumbers list: " + numbers);
	}
}

Output:

ArrayList element: [11, 17, 32, 25, 80, 44]
ArrayList after removing all elements of oddNumbers list: [32, 80, 44]

Remove All throws NullPointerException When Collection is null

Let’s see how removeAll() throws NullPointerException if the specified collection is null.

import java.util.ArrayList;

public class ArrayListRemoveAllDemo {

	public static void main(String[] args) {
		ArrayList<String> alphabates = new ArrayList<>();
		alphabates.add("Z");
		alphabates.add("K");
		alphabates.add("L");
		alphabates.add("D");
		alphabates.add("M");
		alphabates.add("F");

		ArrayList<Integer> vowels = null;

		System.out.println("ArrayList element: " + alphabates);

		alphabates.removeAll(vowels);// throws NullPointerException
	}
}

Output:

ArrayList element: [Z, K, L, D, M, F]
Exception in thread "main" java.lang.NullPointerException
	at java.util.Objects.requireNonNull(Objects.java:203)
	at java.util.ArrayList.removeAll(ArrayList.java:689)
	at ArrayListRemoveAllDemo.main(ArrayListRemoveAllDemo.java:18)

That’s all for this article. Please share it if you like it.

Further References:

ArrayList Documentation.

Categories: Java