Description: The retainAll() method in the List interface is used to retain only the elements from the list that are present in the specified collection.
Example:
List list1 = new ArrayList<>(); list1.add(1); list1.add(2); list1.add(3); list1.add(4); list1.add(5);
List list2 = new ArrayList<>(); list2.add(3); list2.add(4); list2.add(5); list2.add(6); list2.add(7);
list1.retainAll(list2);
System.out.println(list1); // prints [3, 4, 5]
In this example, we have two Lists, list1 and list2. We are using the retainAll() method to retain only the common elements between list1 and list2. After calling the retainAll() method, the resulting list will contain only the elements 3, 4, and 5.
This method is part of the java.util package library.
Java List.retainAll - 20 examples found. These are the top rated real world Java examples of List.retainAll from package OpenDSA-server extracted from open source projects. You can rate examples to help us improve the quality of examples.