java.util.List.retainAll is a method that removes all elements from a list that are not present in another specified collection. This method returns a boolean value based on whether or not the list was modified as a result of this operation.
Example 1: Retaining common elements between two lists
List list1 = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "kiwi")); List list2 = new ArrayList<>(Arrays.asList("banana", "kiwi", "grape", "pear")); boolean modified = list1.retainAll(list2); // Returns true System.out.println(list1); // Outputs [banana, kiwi]
In this example, we have two lists, and we want to retain only the elements that are common in both lists. We call the retainAll method on the first list, passing the second list as the parameter. The resulting list only contains the common elements - "banana" and "kiwi". The return value of the method is "true", indicating that the operation modified the first list.
Example 2: Removing elements that are not in a set
List list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); Set set = new HashSet<>(Arrays.asList(2, 4, 6)); boolean modified = list.retainAll(set); // Returns true System.out.println(list); // Outputs [2, 4]
In this example, we have a list of integers and a set of integers. We want to remove all elements from the list that are not present in the set. We call the retainAll method on the list, passing the set as the parameter. The resulting list only contains the elements that are present in the set - 2 and 4. The return value of the method is "true", indicating that the operation modified the list.
Package library: java.util
Java List.retainAll - 30 examples found. These are the top rated real world Java examples of java.util.List.retainAll extracted from open source projects. You can rate examples to help us improve the quality of examples.