Open In App

How to Handle Null Elements in a PriorityQueue in Java?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, a Priority Queue is an abstract data type similar to a regular queue or stack, but with a key difference like elements are dequeued based on their priority. Regarding the null value property, the PriorityQueue class does not allow null elements. Attempting to add a null element will result in a NullPointerException.

In this article, we will learn How to handle Null Elements in a PriorityQueue in Java.

Handle Null Elements in a PriorityQueue

We cannot directly handle null elements in a PriorityQueue in Java. As per design, the PriorityQueue class does not allow adding null elements. The reasons are given below:

  • Comparison: PriorityQueue relies on comparing elements to determine their priority and maintain the queue order. Comparing an element to null throws a NullPointerException, making the functionality unstable and unpredictable.
  • Special return values: Methods like poll() return null to indicate an empty queue. Adding null elements would conflict with this established behavior and make code harder to understand.

At last, if we want to filter those null values then it all depends on situations where we add the elements to the priority queue.

Program to Handle Null Elements in a PriorityQueue in Java

One of the situations is like if we want to add the List elements (contains NULL values) into the priority queue then we can filter it out by shifting the elements list to the priority queue and based on priority it will handle all the null elements.

Java




// Java Program to Handle Null elements in a PriorityQueue
import java.io.*;
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // ArrayList contains some elements with null values
        ArrayList<Integer> list = new ArrayList<>(
            Arrays.asList(1, null, 3, 4, null, 5, 6));
  
        PriorityQueue<Integer> pq = new PriorityQueue<>();
  
        // Filtering the Null Values while shifting elements
        // list to priority queue.
        for (Integer e : list) {
            if (e != null) {
                pq.add(e);
            }
        }
        
        System.out.println(pq);
    }
}


Output

[1, 3, 4, 5, 6]


Explanation of the above Program:

  • We have an ArrayList named list containing some elements, including null values.
  • Then we have created a PriorityQueue named pq.
  • After creating the Priority Queue, we iterate over the elements of the ArrayList using an enhanced for loop.
  • During the iteration, we checked if each element is not null.
  • If it’s not null, then we have added it to the PriorityQueue.
  • The null elements are filtered out from the list before adding non-null elements to the PriorityQueue.
  • At last, it prints the contents of the PriorityQueue.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads