Skip to content
Related Articles

Related Articles

Improve Article
ArrayList retainAll() method in Java
  • Difficulty Level : Basic
  • Last Updated : 26 Nov, 2018

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 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.






// Program Demonstrate retainAll() method With
// Collection different then 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




// 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)

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :