.retainAll()
Published Mar 8, 2024
Contribute to Docs
The .retainAll()
method of ArrayList
retains only the elements in the ArrayList
that are common to another specified collection. It removes all elements from the ArrayList
that are not present in the specified collection.
Syntax
B.retainAll(Collection c);
B
: The ArrayList whose elements will be retained.c
: The collection whose elements will be retained in the ArrayList B.
Note: Following are the exceptions when using
.retainAll()
method:
ClassCastException
: If the class of an element of thisArrayList
is incompatible with the Passed collection.NullPointerException
: If the list contains a null element and the passed collection does not permit null elements, or if the specified collection is null.
Example
The below example demonstrates the use of .retainAll()
.
// File: RetainAllExample.javaimport java.util.ArrayList;public class RetainAllExample{public static void main(String[] args) {ArrayList<String> list1 = new ArrayList<>();list1.add("apple");list1.add("banana");list1.add("orange");ArrayList<String> list2 = new ArrayList<>();list2.add("banana");list2.add("grape");list2.add("mango");list1.retainAll(list2);System.out.println("List 1 after retainAll : " + list1);System.out.println("List 2 after retainAll : "+list2);}}
The above example gives the following output:
List 1 after retainAll : [banana]List 2 after retainAll : [banana, grape, mango]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Skill path
Build Basic Android Apps with Java
By the end of this Skill Path, you will have created your very own fully functional quiz game for Android Devices with Java.Includes 6 CoursesWith CertificateBeginner Friendly16 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours