📜  Java中的PriorityQueue iterator()方法

📅  最后修改于: 2022-05-13 01:55:08.066000             🧑  作者: Mango

Java中的PriorityQueue iterator()方法

Java.util.PriorityQueue.iterator() 方法用于返回与优先队列相同元素的迭代器。元素从队列中的内容以随机顺序返回。

句法:

Iterator iterate_value = Priority_Queue.iterator();

参数:该函数不带任何参数。

返回值:该方法迭代队列的元素并返回值(迭代器)。

下面的程序说明了Java.util.PriorityQueue.iterator() 方法:
方案一:

// Java code to illustrate iterator()
import java.util.*;
  
public class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue queue = new PriorityQueue();
  
        // Use add() method to add elements into the Queue
        queue.add("Welcome");
        queue.add("To");
        queue.add("Geeks");
        queue.add("4");
        queue.add("Geeks");
  
        // Displaying the PriorityQueue
        System.out.println("PriorityQueue: " + queue);
  
        // Creating an iterator
        Iterator value = queue.iterator();
  
        // Displaying the values after iterating through the queue
        System.out.println("The iterator values are: ");
        while (value.hasNext()) {
            System.out.println(value.next());
        }
    }
}
输出:
PriorityQueue: [4, Geeks, To, Welcome, Geeks]
The iterator values are: 
4
Geeks
To
Welcome
Geeks

方案二:

// Java code to illustrate iterator()
import java.util.*;
  
public class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue queue = new PriorityQueue();
  
        // Use add() method to add elements into the Queue
        queue.add(10);
        queue.add(15);
        queue.add(30);
        queue.add(20);
        queue.add(5);
  
        // Displaying the PriorityQueue
        System.out.println("PriorityQueue: " + queue);
  
        // Creating an iterator
        Iterator value = queue.iterator();
  
        // Displaying the values after iterating through the queue
        System.out.println("The iterator values are: ");
        while (value.hasNext()) {
            System.out.println(value.next());
        }
    }
}
输出:
PriorityQueue: [5, 10, 30, 20, 15]
The iterator values are: 
5
10
30
20
15