Java ArrayList retainAll() method with Examples

ArrayList retainAll() method use for remove from this list all of its elements that are not contained in the given collection.

Syntax :

public boolean retainAll(Collection<?> c)

}
  • Parameters:
    c collection containing elements to be retained in this list
  • Returns Value :
    true if this list changed as a result of the call
  • Exception Throws: It throws following exceptions
    ClassCastException – if the class of an element of this list is incompatible with the specified collection (optional)
    NullPointerException – if this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null

Now will see  ArrayList retainAll() method example in java

import java.util.ArrayList;
import java.util.List;

public class RetainAll {

public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();

// add element in arraylist

arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");
arr.add("delhi");
arr.add("INDIA");

// print arraylist

System.out.println("arrayList is = " + arr);

List<String> brr = new ArrayList<String>();

brr.add("java");
brr.add("shivam");

/*
*  removes from arr all of its elements that are
*  not contained  in the brr.
*/

arr.retainAll(brr);

System.out.println("After retainAll arr is="+arr);

}

}

 

Output:

arrayList is = [c, php, html, java, delhi, INDIA]

After retainAll arr is=[java]

Leave a Reply

Your email address will not be published. Required fields are marked *

34 + = 41