HashSet retainAll(Collection) in Java

retainAll(Collection): This method is available in java.util.HashSet class of Java.

Syntax:

boolean java.util.AbstractCollection.retainAll(Collection<?> c)

This method takes one argument. This method retains only the elements in this collection that are contained in the specified collection

Parameters: One parameter is required for this method.

c: a collection containing elements to be retained in this collection.

Returns: true if this collection changed as a result of the call.

Throws:

1. UnsupportedOperationException - if the retainAll operation is not supported by this collection.

2. ClassCastException - if the types of one or more elements in this collection are incompatible with the specified collection.

3. NullPointerException - if this collection contains one or more null elements and the specified collection does not permit null elements or if the specified collection is null.

Approach 1: When no exception

Java

import java.util.HashSet;

public class HashSetretainAll {
    public static void main(String[] args) {

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");

        HashSet<String> hashSet2 = new HashSet<String>();

        hashSet2.add("Hello");
        hashSet2.add("Java");
        hashSet2.add("C++");
        hashSet2.add("Hello");

        hashSet2.retainAll(hashSet);

        System.out.println(hashSet2);
    }
}

Output:

[Java, Hello]


Approach 2: NullPointerException 

Java

import java.util.HashSet;

public class HashSetretainAll {
    public static void main(String[] args) {

        HashSet<String> hashSet = null;

        HashSet<String> hashSet2 = new HashSet<String>();

        hashSet2.add("Hello");
        hashSet2.add("Java");
        hashSet2.add("C++");
        hashSet2.add("Hello");

        hashSet2.retainAll(hashSet);

        System.out.println(hashSet2);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.AbstractCollection.retainAll(AbstractCollection.java:399)


No comments:

Post a Comment