Java Utility Library

Java PriorityQueue - iterator() Method



The java.util.PriorityQueue.iterator() method returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.

Syntax

public Iterator<E> iterator()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns an iterator over the elements in this queue.

Exception

NA.

Example:

In the example below, the java.util.PriorityQueue.iterator() method returns an iterator over the elements of the given queue.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a priority queue
    PriorityQueue<Integer> PQueue = new PriorityQueue<Integer>();

    //populating the priority queue
    PQueue.add(10);
    PQueue.add(20);
    PQueue.add(30);
    PQueue.add(40);
    PQueue.add(50);

    //print the content of the priority queue
    System.out.println("PQueue contains: " + PQueue);

    //creating an iterator
    Iterator<Integer> itr = PQueue.iterator();

    //print the content of the iterator
    System.out.println("The iterator values are: ");
    while(itr.hasNext())
      System.out.println(itr.next()); 
  }
}

The output of the above code will be:

PQueue contains: [10, 20, 30, 40, 50]
The iterator values are: 
10
20
30
40
50

❮ Java.util - PriorityQueue