In this tutorial, we will learn about the Java ArrayList removeAll() method, and learn how to use this method to remove the elements that match with the any of the elements in the given collection, with the help of examples.

Java ArrayList removeAll() method

ArrayList removeAll() removes from this list all of its elements that are contained in the specified collection.

Syntax

The syntax of removeAll() method is

removeAll(Collection<?> collection)

where

ParameterDescription
collectionThe collection containing elements to be removed from this ArrayList.

Returns

The method returns boolean value.

ADVERTISEMENT

1. removeAll(collection) – Remove elements from the ArrayList that are present in the given collection

In this example, we will take an ArrayList of strings with the elements: "a", "b", "c", "d", "e", "f". We will also take a collection "d", "e", "m". We will remove the elements of this ArrayList which match any of the element in the collection using ArrayList removeAll() method.

Elements "d" and "e" from collection match some of the elements in ArrayList. So, these elements will be removed from the ArrayList.

Element "m" from collection does not match any element from the ArrayList . Nothing happens for this element.

Java Program

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

public class Example {
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>(
				Arrays.asList("a", "b", "c", "d", "e", "f"));		
		List<String> collection = Arrays.asList("d", "e", "m");
		
		System.out.println("Original ArrayList           : " + arrayList);
		arrayList.removeAll(collection);
		System.out.println("ArrayList after removeAll()  : " + arrayList);
	}
}

Output

Original ArrayList           : [a, b, c, d, e, f]
ArrayList after removeAll()  : [a, b, c, f]

Conclusion

In this Java Tutorial, we have learnt the syntax of Java ArrayList removeAll() method, and also learnt how to use this method with the help of Java example programs.