Java ArrayList retainAll() Method
The retainAll() method is used to retain the elements in the arraylist that also exist in the specified collection, that is, to delete those elements that do not exist in the specified collection.
The syntax of the retainAll() method is:
arraylist.retainAll(Collection c);
Note:arraylist is an object of the ArrayList class.
Parameter description:
- collection - the collection parameter
Return Value
Returns true if elements are deleted from the arraylist.
Throws ClassCastException if the elements present in the arraylist class are incompatible with the elements in the specified collection class.
Throws NullPointerException if the arraylist contains null elements and the specified collection does not allow null elements.
Example
Retain the elements in the specified collection:
Example
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("Example");
sites.add("Taobao");
System.out.println("ArrayList 1: " + sites);
// Create another dynamic array
ArrayList<String> sites2 = new ArrayList<>();
// Add elements to the dynamic array
sites2.add("Wiki");
sites2.add("Example");
sites2.add("Google");
System.out.println("ArrayList 2: " + sites2);
// Retain elements
sites.retainAll(sites2);
System.out.println("Retained elements: " + sites);
}
}
Running the above program outputs the result:
ArrayList 1: [Google, Example, Taobao] ArrayList 2: [Wiki, Example, Google] 保留的元素: [Google, Example]
In the above example, we created dynamic arrays named sites and sites2.
Note this line:
sites.retainAll(sites2);
In the example, we passed the array sites2 as a parameter to the retainAll() method. This method deletes from sites the elements that do not exist in sites2.
Common elements of ArrayList and HashSet:
Example
import java.util.HashSet;
class Main {
public static void main(String[] args) {
// Create an array
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements to the array
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("ArrayList: " + numbers);
// Create a HashSet object
HashSet<Integer> primeNumbers = new HashSet<>();
// Add elements to the HashSet
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
System.out.println("HashSet: " + primeNumbers);
// Retain common elements in the arraylist
numbers.retainAll(primeNumbers);
System.out.println("Common elements: " + numbers);
}
}
Running the above program outputs the result:
ArrayList: [1, 2, 3] HashSet: [2, 3, 5] 共有元素: [2, 3]
In the above example, we created an ArrayList named numbers and a HashSet named primeNumbers.
Note this line:
numbers.retainAll(primeNumbers);
In the code, the retainAll() method deletes all elements in the numbers dynamic array that do not exist in primeNumbers.
Other extensions
Java ArrayList