retainAll(Collection c): This retainAll in Java method returns only those elements from the ArrayList which are present in the specified collection.
boolean retainAll(Collection<?> c)
Where c is the collection that you want to retain from the ArrayList.
return type: Its return type is boolean. It can return either true or false.
If specified collection c presents in ArrayList then it returns true after retaining otherwise it returns false.
import java.util.ArrayList;
public class ArraylistExample
{
public static void main(String[] args)
{
ArrayList<Integer> listOfNames = new ArrayList<Integer>();
listOfNames.add(1);
listOfNames.add(2);
listOfNames.add(3);
listOfNames.add(4);
listOfNames.add(5);
listOfNames.add(6);
ArrayList<Integer> listOfNames2 = new ArrayList<Integer>();
listOfNames2.add(4);
listOfNames2.add(5);
listOfNames2.add(6);
listOfNames.retainAll(listOfNames2);
for(Integer number : listOfNames)
System.out.println("Name from list = "+ number);
}
}
Output: Name from list = 4
Name from list = 5
Name from list = 6
