AbstractCollection retainAll() method in Java with Examples
The retainAll() method in AbstractCollection helps in retaining elements of the specified collection from another collection and removes the unmatched elements from the result.
Syntax:
public boolean retainAll(Collection collection)
Parameters: This method accepts a parameter collection which is the collection containing elements that are needed to be retained.
Return Value: The method returns a boolean value. It returns “true” if the elements in the collections are retained successfully and if they aren’t, “false” value is returned.
Exceptions: This method throws following exceptions:
- UnsupportedOperationException: If retainAll() method is not supported by the collection.
- ClassCastException: If the type of any element of the main collection is incompatible with the specified collection(that is to be retained). This is optional.
- NullPointerException: If the main collection consists of any null element and the specified collection doesn’t allow any null value or if the specified collection has null element(s). This is optional.
Below are some examples to illustrate the use of retainAll() method:
Program 1
import java.util.*;
public class AbstractCollectionDemo {
public static void main(String[] args)
{
AbstractCollection<Object> set1
= new ArrayList<Object>();
set1.add( "one" );
set1.add( "two" );
set1.add( "three" );
AbstractCollection<Object> set2
= new ArrayList<Object>();
set2.add( "three" );
set2.add( "one" );
set2.add( "five" );
System.out.println( "Set 1 contains:\n"
+ set1 + "\n" );
System.out.println( "Set 2 contains:\n"
+ set2 + "\n" );
set2.retainAll(set1);
System.out.println( "Set 2 after"
+ " invoking retainAll() method:\n"
+ set2);
}
}
|
Output:
Set 1 contains:
[one, two, three]
Set 2 contains:
[three, one, five]
Set 2 after invoking retainAll() method:
[three, one]
Program 2: To show NullPointerException
import java.util.*;
public class NullPointerExample {
public static void main(String[] args)
{
AbstractCollection<Object> set1 = null ;
AbstractCollection<Object> set2
= new ArrayList<Object>();
set2.add( "one" );
set2.add( "two" );
set2.add( "three" );
System.out.println( "Set 1 contains:"
+ set1 + "\n" );
System.out.println( "Set 2 contains:"
+ set2 + "\n" );
try {
set2.retainAll(set1);
System.out.println( "Set 2 after invoking "
+ "retainAll() method:\n"
+ set2);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
Set 1 contains:null
Set 2 contains:[one, two, three]
java.lang.NullPointerException
Last Updated :
17 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...