The Wayback Machine - https://web.archive.org/web/20240618020205/https://www.geeksforgeeks.org/abstractcollection-retainall-method-in-java-with-examples/
Open In App

AbstractCollection retainAll() method in Java with Examples

Last Updated : 17 Dec, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java program to illustrate retainAll() method
  
import java.util.*;
  
public class AbstractCollectionDemo {
    public static void main(String[] args)
    {
        // Creating an arraylist
        AbstractCollection<Object> set1
            = new ArrayList<Object>();
  
        // adding values in set 1 list
        set1.add("one");
        set1.add("two");
        set1.add("three");
  
        // creating another arraylist
        AbstractCollection<Object> set2
            = new ArrayList<Object>();
  
        // adding values in set 2 list
        set2.add("three");
        set2.add("one");
        set2.add("five");
  
        // before invoking retainAll()
        System.out.println("Set 1 contains:\n"
                           + set1 + "\n");
        System.out.println("Set 2 contains:\n"
                           + set2 + "\n");
  
        // invoking retainAll()
        set2.retainAll(set1);
  
        // after invoking retainAll()
        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




// Java program to illustrate retainAll() method
  
import java.util.*;
  
public class NullPointerExample {
    public static void main(String[] args)
    {
  
        // Creating an arraylist
        // and assigning null to it
        AbstractCollection<Object> set1 = null;
  
        // creating another arraylist
        AbstractCollection<Object> set2
            = new ArrayList<Object>();
  
        // adding values in set 2 list
        set2.add("one");
        set2.add("two");
        set2.add("three");
  
        // before invoking retainAll()
        System.out.println("Set 1 contains:"
                           + set1 + "\n");
        System.out.println("Set 2 contains:"
                           + set2 + "\n");
  
        try {
            // invoking retainAll()
            set2.retainAll(set1);
  
            // after invoking retainAll()
            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


Previous Article
Next Article

Similar Reads

Java 8 | Consumer Interface in Java with Examples
The Consumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result. However these kind of functions don't return any value.Hence this functional interface which takes in one generic namely:-
4 min read
Java 8 | BiConsumer Interface in Java with Examples
The BiConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function that takes in two arguments and produces a result. However, these kinds of functions doesn't return any value. This functional interface takes in two generics, namely:- T:
5 min read
Java 8 | IntToLongFunction Interface in Java with Examples
The IntToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a long-valued result. The lambda expression assigned to an object of IntToLongFunction type is used to define its ap
1 min read
Java Programs - Java Programming Examples
Java is one of the most popular programming languages today because of its simplicity. Java programming concepts such as control statements, Arrays, Strings, Object-Oriented Programming (OOP), etc. are very important from an interview perspective as well as from exams.  So, whether you are a fresher preparing for job interviews or a beginner who ha
12 min read
Java.lang.System.currentTimeMillis() Method with Examples
Before java 8 the compiler used to take it from the java.util package. But later since the use of date and time became important in every software and android application, java developed the date class after java 8. Date and time class via java.util package has been duplicated now. Java uses date and time class after the release of version java 8 t
3 min read
String Class repeat() Method in Java with Examples
The string can be repeated N number of times, and we can generate a new string that has repetitions. repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned. Syntax: string.repeat(count); Parameter: Accepts an intege
2 min read
Java 8 | Arrays parallelSort() method with Examples
Java 8 introduced a new method called as parallelSort() in java.util.Arrays Class. It uses Parallel Sorting of array elements Algorithm of parallelSort() 1. The array is divided into sub-arrays and that sub-arrays is again divided into their sub-arrays, until the minimum level of detail in a set of array. 2. Arrays are sorted individually by multip
4 min read
EnumMap equals() Method in Java with Examples
The Java.util.EnumMap.equals(obj) in Java is used to compare the passed object with this EnumMap for the equality. It must be kept in mind that the object passed must be a map of the same type as the EnumMap.Syntax: boolean equals(Object obj) Parameter: The method takes one parameter obj of Object type and refers to the map to be compared with this
2 min read
EnumMap clear() Method in Java with Examples
The Java.util.EnumMap.clear() method in Java is used to remove all the mappings from the map. The method does not delete the map instead it just clears the map of the mappings. Syntax: enum_map.clear() Parameters: This method does not accept any argument. Return Values: This method does not return any value. Below programs illustrate the working of
2 min read
FloatBuffer array() method in Java With Examples
The array() method of java.nio.FloatBuffer Class is used to Return the float array that backs this buffer. Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa. Invoke() the hasArray() method are used before invoking this method in order to ensure that this buffer has an accessible backing ar
3 min read
Article Tags :