Java ArrayList retainAll() Method Example

Array Methods/APIs Examples


Java ArrayList Examples


ArrayList retainAll() retains only the elements in this list that are contained in the specified method argument collection. Rest all elements are removed from the list. This method is the exact opposite of the removeAll() method.

Java ArrayList retainAll() Method Example

Java program to retain all elements in a list that are present in specified argument collection, using retainAll() method:
import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {

    public static void main(String[] args) {

        List < String > programmingLanguages = new ArrayList < > ();
        programmingLanguages.add("C");
        programmingLanguages.add("C++");
        programmingLanguages.add("Java");
        programmingLanguages.add("Kotlin");

        List < String > programmingLanguages1 = new ArrayList < > ();
        programmingLanguages1.add("Java");
        programmingLanguages1.add("Kotlin");

        programmingLanguages.retainAll(programmingLanguages1);

        programmingLanguages.forEach(key - > System.out.println(key));
    }

}
Output:
Java
Kotlin

Reference

Comments