The PriorityQueue.iterator()
method is present in the PriorityQueue
class, inside the java.util
package.
The PriorityQueue.iterator()
method is used to return an iterator which can be used to iterate over all the elements in the PriorityQueue
class.
The syntax of the PriorityQueue.iterator()
function is as follows:
public Iterator iterator();
The PriorityQueue.iterator()
method does not accept any parameters.
The PriorityQueue.iterator()
method returns an iterator which is used to iterate over all the elements of the PriorityQueue
class. The iterator does not iterate the elements in any specific order.
Let’s look at the code now:
import java.util.*;class Main{public static void main(String[] args){PriorityQueue<Integer> p = new PriorityQueue<Integer>();p.add(2);p.add(28);p.add(6);p.add(80);p.add(28);p.add(7);p.add(15);Iterator i = p.iterator();System.out.print("The elements of priority queue are: ");while (i.hasNext())System.out.print(i.next() + " ");}}
Main
class.main()
function.PriorityQueue
class that consists of Integer type elements.PriorityQueue
class by using the PriorityQueue.add()
method.PriorityQueue
class, using the iterator()
method.while
loop to check the presence of the next element in the PriorityQueue
class with the hasNext()
method, and display the value of the iterator over each element.This is how to use the PriorityQueue.iterator()
method in Java.