What is the ConcurrentLinkedDeque.peekLast() method in Java?
Overview
ConcurrentLinkedDequeis a thread-safe, unboundeddeque. Anullvalue is not permitted as an element in it. We can useConcurrentLinkedDequewhen multiple threads are sharing a singledeque.
The peekLast method can be used to get the last element of the ConcurrentLinkedDeque object.
Syntax
public E peekLast()
Parameters
This method doesn’t take an argument.
Return value
This method retrieves the last element of the deque object. If the deque is empty, then null is returned.
This method is similar to the
getLastmethod. They only differ in the fact that thepeekLastmethod returnsnullif thedequeis empty, whereas thegetLastmethod throws aNoSuchElementExceptionerror if thedequeis empty.
Code
The code given below shows us how to use the peekLast method:
import java.util.concurrent.ConcurrentLinkedDeque;class PeekLast {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.peekLast() returns : " + deque.peekLast());}}
Explanation
-
Line 1: We import the
ConcurrentLinkedDequeclass. -
Line 4: We create a
ConcurrentLinkedDequeobject with the namedeque. -
Lines 5–7: We use the
add()method of thedequeobject to add three elements ("1","2","3") to thedeque. -
Line 10: We use the
peekLast()method of thedequeobject to get the last element of thedeque. In this case,3will be returned.