Java ArrayList.retainAll() – Examples

In this tutorial, we will learn about the Java ArrayList.retainAll() method, and learn how to use this method to retain only the elements in this ArrayList that are contained in the specified collection, with the help of examples.

retainAll(Collection)

ArrayList.retainAll() retains only the elements in this ArrayList that are contained in the specified collection.

Syntax

The syntax of retainAll() method is

retainAll(Collection<?> collection)

where

ParameterDescription
collectionThe collection containing elements to be retained in this ArrayList.

Returns

The method returns boolean value.

Example 1 – retainAll(collection)

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

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", "d", "c", "f"));		
		List<String> collection = Arrays.asList("c" ,"a", "d");
		
		System.out.println("Original ArrayList           : " + arrayList);
		boolean value = arrayList.retainAll(collection);
		System.out.println("Returned value : " + value);
		System.out.println("ArrayList after retainAll()  : " + arrayList);
	}
}

Output

Original ArrayList           : [a, b, c, d, e, d, c, f]
Returned value : true
ArrayList after retainAll()  : [a, c, d, d, c]

Conclusion

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