What is the PriorityQueue.iterator() method in Java?
Introduction
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.
Syntax
The syntax of the PriorityQueue.iterator() function is as follows:
public Iterator iterator();
Parameters
The PriorityQueue.iterator() method does not accept any parameters.
Return value
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.
Code
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() + " ");}}
Code explanation
- Line 1: We import the required package.
- Line 2: We make a
Mainclass. - Line 4: We make a
main()function. - Line 6: We declare a
PriorityQueueclass that consists of Integer type elements. - Lines 8 to 14: We insert the elements in the
PriorityQueueclass by using thePriorityQueue.add()method. - Line 16: We declare an iterator for the
PriorityQueueclass, using theiterator()method. - Lines 20 to 21: We use a
whileloop to check the presence of the next element in thePriorityQueueclass with thehasNext()method, and display the value of the iterator over each element.
This is how to use the PriorityQueue.iterator() method in Java.