Java Set retainAll() Method Tutorial

In this section, we will learn what the Set retainAll() method is and how to use it in Java.

What is Java retainAll() Method?

The Java retainAll() method takes a reference to a collection object and compares the entire elements in the collection with the elements of a Set. For any element in the target Set object that wasn’t in the reference collection, it will be removed!

So in short, the retainAll() method is used to retain those elements of a Set object that are also shared in the specified collection object.

Java Set retainAll() Method Syntax:

boolean retainAll(Collection<?> c)

retainAll() Method Parameters:

The method takes one argument and that is a reference to a collection that we want to compare its elements with the target Set object.

retainAll() Method Return Value:

The return value of this method is of boolean type.

If one or more elements of the target Set object were removed as a result of invoking this method, then the final result will be true, otherwise the value false will return instead.

retainAll() Method Exceptions:

The method might throw three types of exceptions:

UnsupportedOperationException – We get this exception if the target Set object does not support this method.

ClassCastException – We get this exception if the reference collection is of incompatible type compared to the elements of the target Set object.

NullPointerException – We get this exception if the argument is a null value.

Example: using Set retainAll() method

import java.util.HashSet;
import java.util.Set; 
import java.util.ArrayList;
class Main{
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(0);
        set.add(10);

        ArrayList<Integer> array = new ArrayList<>();
        array.add(10);
        array.add(0);
        array.add(20);
        
        set.retainAll(array);

        for (int i: set){
            System.out.println(i);
        }		
    }
        
}

Output:

0

10

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies