PriorityQueue removeAll(Collection) in Java

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

Syntax:

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

This method takes one argument. This method removes all of this collection's elements that are also contained in the specified collection.

Parameters: One parameter is required for this method.

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

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

Throws:

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

Approach 1: When no exception

Java

import java.util.Collection;
import java.util.PriorityQueue;

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

        PriorityQueue<Integer> priorityQueue =
new PriorityQueue<Integer>();

        priorityQueue.add(12);
        priorityQueue.add(5);
        priorityQueue.add(10);
        priorityQueue.add(2);

        Collection<Integer> c =
new PriorityQueue<Integer>();

        c.add(12);
        c.add(5);

        System.out.println(priorityQueue.removeAll(c));

    }
}

Output:

true


Approach 2: NullPointerException

Java

import java.util.Collection;
import java.util.PriorityQueue;

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

        PriorityQueue<Integer> priorityQueue =
new PriorityQueue<Integer>();

        priorityQueue.add(12);
        priorityQueue.add(5);
        priorityQueue.add(10);
        priorityQueue.add(2);

        Collection<Integer> c = null;

        System.out.println(priorityQueue.removeAll(c));

    }
}

Output:

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


No comments:

Post a Comment