PriorityQueue forEach(Consumer) in Java

forEach(Consumer): This method is available in java.util.PriorityQueue class of Java.

Syntax:

void java.util.PriorityQueue.forEach(Consumer<? super K> action)

This method takes one argument. This method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Parameters: One parameter is required for this method.

action: The action to be performed for each element.

Returns: NA

Throws:

NullPointerException - if the specified action is null

Approach 1: When no exception

Java

import java.util.PriorityQueue;

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

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

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

        priorityQueue.forEach((n -> System.out.print(n + " ")));

    }
}

Output:

2 5 10 12 

Approach 2: NullPointerException

Java

import java.util.PriorityQueue;

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

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

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

        priorityQueue.forEach(null);

    }
}

Output:

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


No comments:

Post a Comment