What is the ConcurrentLinkedDeque.peek() method in Java?
ConcurrentLinkedDequeis thread-safe, unbounded deque. Thenullvalue is not permitted as an element. We can useConcurrentLinkedDequewhen multiple threads share a single deque.
The peek method can be used to get the first element of the ConcurrentLinkedDeque object.
Syntax
public E peek()
Parameters
This method doesn’t take any parameters.
Return value
The peek method retrieves the first element of the deque object. If the deque is empty, then peek returns null
Code
The code below demonstrates how to use the peek method.
import java.util.concurrent.ConcurrentLinkedDeque;class Peek {public static void main( String args[] ) {ConcurrentLinkedDeque<String> deque = new ConcurrentLinkedDeque<>();deque.add("1");deque.add("2");deque.add("3");System.out.println("The deque is " + deque);System.out.println("deque.peek() returns : " + deque.peek());}}
Explanation
-
Line 1: We import the
ConcurrentLinkedDequeclass. -
Line 4: We create a
ConcurrentLinkedDequeobject with the namedeque. -
Lines 5 to 7: We use the
add()method of thedequeobject to add three elements ("1","2","3") to thedeque. -
Line 10: We use the
peek()method of thedequeobject to get the first element of thedeque. In our case,peek()returns1.