PriorityBlockingQueue peek() method in Java
The peek() method of PriorityBlockingQueue returns the element at head of the PriorityBlockingQueue. It retrieves the value of the head of LinkedBlockingQueue but does not remove it. If the PriorityBlockingQueue does not contains any element, then this method returns null. A PriorityBlockingQueue queue uses the same ordering rules as class PriorityQueue.
Syntax:
public E peek()
Parameter: This method does not take any parameter.
Returns: This method returns the head of the PriorityBlockingQueue.
Below program illustrate peek() method of PriorityBlockingQueue.
Example 1:
import java.util.concurrent.PriorityBlockingQueue;
public class GFG {
public static void main(String[] args)
{
int capacityOfQueue = 5 ;
PriorityBlockingQueue<Integer> PrioQueue
= new PriorityBlockingQueue<Integer>(capacityOfQueue);
PrioQueue.add( 464161 );
PrioQueue.add( 416165 );
System.out.println( "PrioQueue: " + PrioQueue);
int head = PrioQueue.peek();
System.out.println( "Head of Queue: " + head);
}
}
|
Output:
PrioQueue: [416165, 464161]
Head of Queue: 416165
Example 2: To illustrate peek() method of PriorityBlockingQueue which contains list of names.
import java.util.concurrent.PriorityBlockingQueue;
public class GFG {
public static void main(String[] args)
{
int capacityOfQueue = 5 ;
PriorityBlockingQueue<String> names
= new PriorityBlockingQueue<String>(capacityOfQueue);
names.add( "Geeks" );
names.add( "forGeeks" );
names.add( "A" );
names.add( "Computer" );
names.add( "Portal" );
System.out.println( "List of Names: " + names.toString());
String head = names.peek();
System.out.println( "Head of Queue: " + head);
names.poll();
System.out.println( "First Name from head is removed" );
System.out.println( "List of Names: " + names.toString());
head = names.peek();
System.out.println( "Head of Queue: " + head);
}
}
|
Output:
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
Reference:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html#peek–
Last Updated :
26 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...