El método peek() de PriorityBlockingQueue devuelve el elemento al principio de PriorityBlockingQueue. Recupera el valor del encabezado de LinkedBlockingQueue pero no lo elimina. Si PriorityBlockingQueue no contiene ningún elemento, este método devuelve un valor nulo. Una cola PriorityBlockingQueue utiliza las mismas reglas de ordenación que la clase PriorityQueue.
Sintaxis:
public E peek()
Parámetro: Este método no toma ningún parámetro.
Devoluciones: este método devuelve el encabezado de PriorityBlockingQueue.
El siguiente programa ilustra el método peek() de PriorityBlockingQueue.
Ejemplo 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
Ejemplo 2: Para ilustrar el método peek() de PriorityBlockingQueue que contiene una lista de nombres.
// 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
Referencia:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html#peek–
Publicación traducida automáticamente
Artículo escrito por AmanSingh2210 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA