Open In App

How to Iterate over the Elements of a PriorityQueue in Java?

Last Updated : 27 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, a Priority Queue is a Data structure that allows the users to store data based on their priority so that the elements with the highest priority can be accessed in constant time. In this article, we will learn how to iterate over the elements of a PriorityQueue in Java.

Example

Input: PriorityQueue pq ={1,2,3,4,5}
Output: Elements of pq: 1 2 3 4 5

Iterate Over the Elements of a PriorityQueue

To iterate over the elements of a PriorityQueue in Java, we can create an iterator and then traverse and access each element present in the PriorityQueue with the help of the hasNext function. Let us understand this with the help of the below program:

Java Program to Iterate Over the Elements of a PriorityQueue

The following program demonstrates how we can iterate over the elements of a PriorityQueue in Java:

Java
// Java Program to Iterate over the
// Elements of a PriorityQueue
import java.util.PriorityQueue;
import java.util.Iterator;

// Driver Class
public class PriorityQueueIteration {
      // main function
    public static void main(String[] args) {
        // Create a PriorityQueue of Integer
        PriorityQueue<Integer> pq = new PriorityQueue<>();

        // Add some elements to the PriorityQueue
        pq.add(1);
        pq.add(2);
        pq.add(3);
        pq.add(4);
        pq.add(5);

        // Create an iterator to iterate over
          // the elements of the PriorityQueue
        Iterator<Integer> it = pq.iterator();

        // Iterate over the elements using the iterator
        System.out.println("Elements of the PriorityQueue pq:");
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
    }
}

Output
Elements of the PriorityQueue pq:
1 2 3 4 5 

Complexity of the above Program:

Time Complexity: O(N), where N is the size of the PriorityQueue
Auxiliary Space: O(1).

Explanation of the above Program:

  • We declared a PriorityQueue pq of interger type and added some elements in it.
  • We initialized an iterator it for the PriorityQueue to iterate over it’s elements.
  • With the help of hasNext function we moved the iterator it over the elements of the PriorityQueue pq and printed them.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads