English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList retainAll() method only retains those elements that exist in both the ArrayList and the specified collection.
In addition, all elements that do not appear in the specified collection are deleted from the arraylist.
The syntax of the retainAll() method is:
arraylist.retainAll(Collection c);
collection- Only elements existing in the set are retained in the arraylist.
If an element is removed from the arraylist, it returns true
If the element class existing in arraylist is not compatible with the specifiedSetIf the element class existing in arraylist is not compatible with the specified
If the arraylist contains null elements and the specifiedSetDoes not allow null elements, and throws NullPointerException
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create ArrayList ArrayList<String> languages1 = new ArrayList<>(); //Add elements to ArrayList languages1.add("JavaScript"); languages1.add("Python"); languages1.add("Java"); System.out.println("ArrayList 1: " + languages1); //Create another ArrayList ArrayList<String> languages2 = new ArrayList<>(); //Add elements to ArrayList languages2.add("English"); languages2.add("Java"); languages2.add("Python"); System.out.println("ArrayList 2: " + languages2); //Retain common elements languages1.retainAll(languages2); System.out.println("Common elements: " + languages1); } }
Output Result
ArrayList 1: [JavaScript, Python, Java] ArrayList 2: [English, Java, Python] Common elements: [Python, Java]
In the above example, we created two ArrayLists named languages1and languages2ArrayList. Note this line,
languages1.retainAll(languages2);
Here, we will use arraylist languages2as an argument to the retainAll() method. This method removes elements from languages1Remove elements not present in languages2Keep only the common elements.
import java.util.ArrayList; import java.util.HashSet; class Main { public static void main(String[] args) { //Create ArrayList ArrayList<Integer> numbers = new ArrayList<>(); //Add elements to ArrayList numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("ArrayList: " + numbers); //Create a HashSet 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 ArrayList numbers.retainAll(primeNumbers); System.out.println("Common elements: " + numbers); } }
Output Result
ArrayList: [1, 2, 3] HashSet: [2, 3, 5] Common elements: [2, 3]
In the above example, we created an arraylist named numbers and a hash set named primeNumbers. Note this line,
numbers.retainAll(primeNumbers);
Here, the retainAll() method will remove all those elements that do not exist in primeNumbers and retain only the common elements. Therefore,2And3Kept in the arraylist numbers.