The Wayback Machine - https://web.archive.org/web/20241126211326/https://www.geeksforgeeks.org/arraylist-retainall-method-in-java/
Open In App

ArrayList retainAll() method in Java

Last Updated : 03 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The retainAll() method of ArrayList is used to remove all the array list’s elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method. Syntax:

public boolean retainAll(Collection C)

Parameters: The C is the collection containing elements to be retained in the list. Return Value: The method returns a boolean value true if the list is changed at all as a result of the call else false. Exceptions:

  1. ClassCastException: If the class of an element of this ArrayList is incompatible with the Passed collection. This is optional.
  2. NullPointerException: If the list contains a null element and the passed collection does not permit null elements, or if the specified collection is null. This is also optional.

Below programs are used to illustrate the Java.util.ArrayList.retainAll() method: Program 1: Passing ArrayList collection as parameter to method. 

Java




// Java code to illustrate retainAll() method
import java.util.ArrayList;
public class GFG {
    public static void main(String[] args)
    {
        // Creating an empty array list
        ArrayList<String> bags = new ArrayList<String>();
 
        // Add values in the bags list.
        bags.add("pen");
        bags.add("pencil");
        bags.add("paper");
 
        // Creating another array list
        ArrayList<String> boxes = new ArrayList<String>();
 
        // Add values in the boxes list.
        boxes.add("pen");
        boxes.add("paper");
        boxes.add("books");
        boxes.add("rubber");
 
        // Before Applying method print both lists
        System.out.println("Bags Contains :" + bags);
        System.out.println("Boxes Contains :" + boxes);
 
        // Apply retainAll() method to boxes passing bags as parameter
        boxes.retainAll(bags);
 
        // Displaying both the lists after operation
        System.out.println("\nAfter Applying retainAll()"+
        " method to Boxes\n");
        System.out.println("Bags Contains :" + bags);
        System.out.println("Boxes Contains :" + boxes);
    }
}


Output:

Bags Contains :[pen, pencil, paper]
Boxes Contains :[pen, paper, books, rubber]

After Applying retainAll() method to Boxes

Bags Contains :[pen, pencil, paper]
Boxes Contains :[pen, paper]

Program 2: Passing Collection different than ArrayList as parameter to method. 

Java




// Program Demonstrate retainAll() method With
// Collection different than ArrayList as a parameter of the method
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Creating an empty array list
        HashSet<String> bags = new HashSet<String>();
 
        // Add values in the bags Set.
        bags.add("pen");
        bags.add("ink");
        bags.add("paper");
 
        // Creating another empty array list
        ArrayList<String> boxes = new ArrayList<String>();
 
        // Add values in the boxes list.
        boxes.add("pen");
        boxes.add("paper");
        boxes.add("books");
        boxes.add("rubber");
        boxes.add("ink");
 
        // Before Applying method print both list and set.
        System.out.println("Bags Contains :" + bags);
        System.out.println("Boxes Contains :" + boxes);
 
        // Apply retainAll() method to boxes passing bags as parameter
        boxes.retainAll(bags);
 
        // Displaying both the lists after operation
        System.out.println("\nAfter Applying retainAll()" +
        " method to Boxes\n");
        System.out.println("Bags Contains :" + bags);
        System.out.println("Boxes Contains :" + boxes);
    }
}


Output:

Bags Contains :[paper, ink, pen]
Boxes Contains :[pen, paper, books, rubber, ink]

After Applying retainAll() method to Boxes

Bags Contains :[paper, ink, pen]
Boxes Contains :[pen, paper, ink]

Program 3: Illustrating the error thrown by retainAll() method 

Java




// Program to illustrate error thrown by retainAll() method
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Creating an empty array list
        ArrayList<Integer> list1 = null;
 
        /// Creating another empty array list
        ArrayList<String> list2 = new ArrayList<String>();
 
        // Add values in the list2 list.
        list2.add("pen");
        list2.add("paper");
        list2.add("books");
        list2.add("rubber");
 
        // Before Applying method print both lists
        System.out.println("list1 Contains :" + list1);
        System.out.println("list2 Contains :" + list2);
 
        // Apply retainAll() method to list2 passing list1 as parameter
        list2.retainAll(list1);
 
        // Displaying both the lists after operation
        System.out.println("\nAfter Applying retainAll()"+
        " method to list2\n");
        System.out.println("list1 Contains :" + list1);
        System.out.println("list2 Contains :" + list2);
    }
}


Output:

list1 Contains :null
list2 Contains :[pen, paper, books, rubber]

Runtime Error:

Exception in thread "main" java.lang.NullPointerException
    at java.util.Objects.requireNonNull(Objects.java:203)
    at java.util.ArrayList.retainAll(ArrayList.java:714)
    at GFG.main(GFG.java:26)

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#retainAll(java.util.Collection)



Previous Article
Next Article

Similar Reads

LinkedHashSet retainAll() method in Java with Example
The retainAll() method of java.util.LinkedHashSet class is used to retain from this set all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this set. Returns Value: This method returns true
3 min read
AbstractSet retainAll() method in Java with Example
The retainAll() method of java.util.AbstractSet class is used to retain from this set all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this set. Returns Value: This method returns true i
3 min read
Stack retainAll() method in Java with Example
The retainAll() method of java.util.Stack class is used to retain from this stack all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this stack. Returns Value: This method returns true if
3 min read
HashSet retainAll() method in Java with Example
The retainAll() method of java.util.HashSet class is used to retain from this set all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this set. Returns Value: This method returns true if th
3 min read
AbstractSequentialList retainAll() method in Java with Example
The retainAll() method of java.util.AbstractSequentialList class is used to retain from this list all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this list. Returns Value: This method r
3 min read
CopyOnWriteArraySet retainAll() method in Java with Example
The retainAll() method of java.util.concurrent.CopyOnWriteArraySet class is used to retain from this set all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this set. Returns Value: This me
3 min read
CopyOnWriteArrayList retainAll() method in Java with Examples
The Java.util.concurrent.CopyOnArrayList.retainAll() method in Java is used to retain only the elements in the list that are contained in specific collection. Syntax: public boolean retainAll(Collection col) Parameters: This method accepts a mandatory parameter col which is of the type of collection. This is the collection of elements to be retaine
2 min read
TreeSet retainAll() method in Java with Example
The retainAll() method of java.util.TreeSet class is used to retain from this set all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this set. Returns Value: This method returns true if th
3 min read
Set retainAll() method in Java with Example
The retainAll() method of java.util.Set interface is used to retain from this set all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this set. Return Value: This method returns true if thi
3 min read
List retainAll() Method in Java with Examples
This method is used to retain all the elements present in the collection from the specified collection into the list. Syntax: boolean retainAll(Collection c) Parameters: This method has only argument, collection of which elements are to be retained in the given list. Returns: This method returns True if elements are retained and list changes. Below
2 min read
Vector retainAll() method in Java with Examples
The retainAll method of class vector in java is an inbuilt function in Java which is used to retains only the elements in this Vector that are contained in the specified Collection. In other words, removes from this Vector all of its elements that are not contained in the specified Collection. Syntax: public boolean retainAll(Collection c) Paramete
3 min read
LinkedTransferQueue retainAll() method in Java with Examples
The retainAll() method of java.util.concurrent.LinkedTransferQueue is an in-built function in Java which is used to retain all the elements in this queue which are common to both i.e. the specified collection and this queue. All other elements which are not common are removed from this queue. Syntax: public boolean retainAll(Collection C) Parameter
3 min read
LinkedBlockingDeque retainAll() method in Java with Examples
The retainAll() method of LinkedBlockingDeque is an in-built function is Java which is used to remove from this deque all of its elements that are contained in the specified collection. That means, all the common elements these two collections are removed from this deque. Syntax: public boolean retainAll(Collection c) Parameters: This method takes
2 min read
SortedSet retainAll() method in Java with Examples
The retainAll() method of SortedSet interface is used to retain from this SortedSet, all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this SortedSet. Return Value: This method returns tr
3 min read
Java Collection retainAll() Method
In Java, the retainAll() method of Java Collection retains or keeps only those elements present inside the collection which is given as an argument to the function. Syntax for retainAll() method: boolean retainAll(Collection<?> c);Parameters: c is the collection containing elements retained or kept by the calling collection. Return Type:It re
3 min read
Java.util.ArrayList.add() Method in Java
Below are the add() methods of ArrayList in Java: boolean add(Object o) : This method appends the specified element to the end of this list. Parameters: object o: The element to be appended to this list. Exception: NA // Java code to illustrate add(Object o) import java.io.*; import java.util.ArrayList; public class ArrayListDemo { public static vo
2 min read
Java.util.ArrayList.addall() method in Java
Below are the addAll() methods of ArrayList in Java: boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behavior of this operation is undefined if the specified collection is modified while the ope
4 min read
Java.util.Arraylist.indexOf() in Java
The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for. // Java code to demonstrate the working of // indexOf in ArrayList // for ArrayList functions import java.util.Arra
2 min read
ArrayList get(index) Method in Java with Examples
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Syntax: get(index) Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list. Exception: It throws IndexOutOfBoundsException if the index is out of range (index=size(
2 min read
ArrayList clear() Method in Java with Examples
The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so whenever this operation has been performed all elements of the corresponding ArrayList will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimiz
2 min read
ArrayList spliterator() method in Java
The spliterator() method of ArrayList returns a Spliterator of the same elements as ArrayList but created Spliterator is late-binding and fail-fast. A late-binding Spliterator binds to the source of elements. It means that Arraylist at the point of the first traversal, first split, or the first query for estimated size, rather than at the time the
3 min read
ArrayList forEach() method in Java
The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised. The operation is performed in the order of iteration if that order is specified by the method. Exceptio
2 min read
ArrayList removeIf() method in Java
The removeIf() method of ArrayList is used to remove all of the elements of this ArrayList that satisfies a given predicate filter which is passed as a parameter to the method. Errors or runtime exceptions are thrown during iteration or by the predicate are pass to the caller. This method returns True, if we are able to remove some element. Java 8
3 min read
ArrayList iterator() method in Java with Examples
The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast. Syntax: Iterator iterator() Parameter: This method do not accept any parameter. Return Value: This method returns an iterator over the elements in this list in proper
2 min read
ArrayList ensureCapacity() method in Java with Examples
The ensureCapacity() method of java.util.ArrayList class increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. Syntax: public void ensureCapacity(int minCapacity) Parameters: This method takes the desired minimum capacity as a parameter
2 min read
ArrayList removeAll() method in Java with Examples
The removeAll() method of java.util.ArrayList class is used to remove from this list all of its elements that are contained in the specified collection. Syntax: public boolean removeAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be removed from this list. Returns Value: This method returns true if
3 min read
ArrayList listIterator() method in Java with Examples
listIterator() The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast. Syntax: public ListIterator listIterator() Return Value: This method returns a list iterator over the elements in this list (in proper sequence). Below
3 min read
ArrayList set() method in Java with Examples
The set() method of java.util.ArrayList class is used to replace the element at the specified position in this list with the specified element. Syntax: public E set(int index, E element) Parameters: This method takes the following argument as a parameter. index- index of the element to replace element- element to be stored at the specified position
2 min read
ArrayList size() method in Java with Examples
The size() method of java.util.ArrayList class is used to get the number of elements in this list. Syntax: public int size() Returns Value: This method returns the number of elements in this list. Below are the examples to illustrate the size() method. Example 1: // Java program to demonstrate // size() method // for Integer value import java.util.
2 min read
ArrayList subList() method in Java with Examples
The subList() method of java.util.ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this li
3 min read
three90RightbarBannerImg