Java PriorityBlockingQueue peek()方法
PriorityBlockingQueue 的 peek() 方法返回PriorityBlockingQueue中 头部 的元素。它检索LinkedBlockingQueue的头部的值,但不删除它。如果PriorityBlockingQueue不包含任何元素,那么这个方法返回null。PriorityBlockingQueue队使用与PriorityQueue类相同的排序规则。
语法
public E peek()
参数: 该方法不接受任何参数。
返回: 该方法返回PriorityBlockingQueue的头部。
下面的程序说明了PriorityBlockingQueue的peek()方法。
例1 :
// Java Program Demonstrate peek()
// method of PriorityBlockingQueue
import java.util.concurrent.PriorityBlockingQueue;
public class GFG {
public static void main(String[] args)
{
// define capacity of PriorityBlockingQueue
int capacityOfQueue = 5;
// create object of PriorityBlockingQueue
PriorityBlockingQueue<Integer> PrioQueue
= new PriorityBlockingQueue<Integer>(capacityOfQueue);
// Add elements to PriorityBlockingQueue
PrioQueue.add(464161);
PrioQueue.add(416165);
// print PrioQueue
System.out.println("PrioQueue: " + PrioQueue);
// get head of PriorityBlockingQueue
int head = PrioQueue.peek();
// print head of PriorityBlockingQueue
System.out.println("Head of Queue: " + head);
}
}
输出:
PrioQueue: [416165, 464161]
Head of Queue: 416165
例2: 说明PriorityBlockingQueue的peek()方法,该方法包含名字的列表。
// Java Program Demonstrate peek()
// method of PriorityBlockingQueue
import java.util.concurrent.PriorityBlockingQueue;
public class GFG {
public static void main(String[] args)
{
// define capacity of PriorityBlockingQueue
int capacityOfQueue = 5;
// create object of PriorityBlockingQueue
PriorityBlockingQueue<String> names
= new PriorityBlockingQueue<String>(capacityOfQueue);
// Add names of students of girls college
names.add("Geeks");
names.add("forGeeks");
names.add("A");
names.add("Computer");
names.add("Portal");
// print PrioQueue
System.out.println("List of Names: " + names.toString());
// get head of PriorityBlockingQueue
String head = names.peek();
// print head of PriorityBlockingQueue
System.out.println("Head of Queue: " + head);
// remove one name from head
names.poll();
System.out.println("First Name from head is removed");
// print PrioQueue
System.out.println("List of Names: " + names.toString());
// get head of PriorityBlockingQueue
head = names.peek();
// print head of PriorityBlockingQueue
System.out.println("Head of Queue: " + head);
}
}
输出:
List of Names: [A, Computer, Geeks, forGeeks, Portal]
Head of Queue: A
First Name from head is removed
List of Names: [Computer, Portal, Geeks, forGeeks]
Head of Queue: Computer
参考资料:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html#peek-