LinkedHashSet removeAll(Collection) in Java

removeAll(Collection): This method is available in java.util.LinkedHashSet class of Java.

Syntax:

boolean java.util.AbstractSet.removeAll(Collection<?> c)

This method takes one argument. This method removes from this set all of its elements that are contained in the specified collection

Parameters: One parameter is required for this method.

c: a collection containing elements to be removed from this set.

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

Throws:

1. UnsupportedOperationException - if the removeAll operation is not supported by this set.

2. ClassCastException - if the class of an element of this set is incompatible with the specified collection.

3. NullPointerException - if this set contains a null element 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.Collection;
import java.util.LinkedHashSet;

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

        LinkedHashSet<String> linkedHashSet =
new LinkedHashSet<>();

        Collection<String> collection =
new LinkedHashSet<String>();
        collection.add("Java");
        collection.add("C++");
        linkedHashSet.add("Hello");
        linkedHashSet.removeAll(collection);
        System.out.println(linkedHashSet);

    }
}

Output:

[Hello]


Approach 2: NullPointerException

Java

import java.util.Collection;
import java.util.LinkedHashSet;

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

        LinkedHashSet<String> linkedHashSet =
new LinkedHashSet<>();

        Collection<String> collection = null;
        linkedHashSet.add("Hello");
        linkedHashSet.removeAll(collection);
        System.out.println(linkedHashSet);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.AbstractSet.removeAll(AbstractSet.java:167)


No comments:

Post a Comment