The peek() method of LinkedBlockingQueue returns the head of the LinkedBlockingQueue. It retrieves the value of the head of LinkedBlockingQueue but does not remove it. If the LinkedBlockingQueue is empty then this method returns null.
Syntax:
public E peek()
Return Value: This method returns the head of the LinkedBlockingQueue.
Below programs illustrates peek() method of LinkedBlockingQueue class:
Program 1: Returning the head of the LinkedBlockingQueue using peek() method where LinkedBlockingQueue of capacity 7 contains list of names
import java.util.concurrent.LinkedBlockingQueue;
public class GFG {
public static void main(String[] args)
{
int capacityOfQueue = 7 ;
LinkedBlockingQueue<String> linkedQueue
= new LinkedBlockingQueue<String>(capacityOfQueue);
linkedQueue.add( "John" );
linkedQueue.add( "Tom" );
linkedQueue.add( "Clark" );
linkedQueue.add( "Kat" );
String head = linkedQueue.peek();
System.out.println( "Queue is " + linkedQueue);
System.out.println( "Head of Queue is " + head);
linkedQueue.remove();
head = linkedQueue.peek();
System.out.println( "\nRemoving one element from Queue\n" );
System.out.println( "Queue is " + linkedQueue);
System.out.println( "Head of Queue is " + head);
}
}
|
Output:
Queue is [John, Tom, Clark, Kat]
Head of Queue is John
Removing one element from Queue
Queue is [Tom, Clark, Kat]
Head of Queue is Tom
Program 2: Finding head of LinkedBlockingQueue which contains list of Employees
Output:
Head of list
Employee Name : Ravi
Employee Position : Tester
Employee Salary : 39000
Removing one element from Queue
Head of list
Employee Name : Sanjeet
Employee Position : Manager
Employee Salary : 98000
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingQueue.html#peek–
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!