The peek() method of ConcurrentLinkedQueue is used to return the head of the ConcurrentLinkedQueue. It retrieves but does not remove, the head of this ConcurrentLinkedQueue. If the ConcurrentLinkedQueue is empty then this method returns null.
Syntax:
public E peek()
Returns: This method returns the head of this ConcurrentLinkedQueue without removing it.
Below programs illustrate peek() method of ConcurrentLinkedQueue:
Example 1:
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args)
{
ConcurrentLinkedQueue<Integer>
queue = new ConcurrentLinkedQueue<Integer>();
queue.add( 4353 );
queue.add( 7824 );
queue.add( 78249 );
queue.add( 8724 );
System.out.println( "ConcurrentLinkedQueue: " + queue);
int response1 = queue.peek();
System.out.println( "Head: " + response1);
System.out.println( "ConcurrentLinkedQueue after peek: " + queue);
}
}
|
Output:
ConcurrentLinkedQueue: [4353, 7824, 78249, 8724]
Head: 4353
ConcurrentLinkedQueue after peek: [4353, 7824, 78249, 8724]
Example 2:
import java.util.concurrent.*;
public class GFG {
public static void main(String[] args)
{
ConcurrentLinkedQueue<String>
queue = new ConcurrentLinkedQueue<String>();
queue.add( "Aman" );
queue.add( "Amar" );
queue.add( "Sanjeet" );
queue.add( "Rabi" );
System.out.println( "ConcurrentLinkedQueue: " + queue);
String response1 = queue.peek();
System.out.println( "Head: " + response1);
System.out.println( "ConcurrentLinkedQueue after peek: " + queue);
queue.poll();
queue.poll();
System.out.println( "Updated ConcurrentLinkedQueue: " + queue);
String response2 = queue.peek();
System.out.println( "Head: " + response1);
System.out.println( "ConcurrentLinkedQueue after peek: " + queue);
}
}
|
Output:
ConcurrentLinkedQueue: [Aman, Amar, Sanjeet, Rabi]
Head: Aman
ConcurrentLinkedQueue after peek: [Aman, Amar, Sanjeet, Rabi]
Updated ConcurrentLinkedQueue: [Sanjeet, Rabi]
Head: Aman
ConcurrentLinkedQueue after peek: [Sanjeet, Rabi]
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.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!
Last Updated :
26 Nov, 2018
Like Article
Save Article