Retains only the elements in this list that are contained in the specified collection. In other words, removes from this list all of its elements that are not contained in the specified collection.
Examples
package com.logicbig.example.arraylist;
import java.util.*;
public class RetainAllExample {
public static void main(String... args) { // Keep only elements present in another collection ArrayList<String> list = new ArrayList<>(Arrays.asList("A","B","C","D","E")); List<String> toKeep = Arrays.asList("B", "D", "F"); list.retainAll(toKeep); System.out.println("After retainAll: " + list); } }