What is the ConcurrentLinkedDeque.peekLast() method in Java?

Share

Overview

ConcurrentLinkedDeque is a thread-safe, unbounded deque. A null value is not permitted as an element in it. We can use ConcurrentLinkedDeque when multiple threads are sharing a single deque.

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 getLast method. They only differ in the fact that the peekLast method returns null if the deque is empty, whereas the getLast method throws a NoSuchElementException error if the deque is 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 ConcurrentLinkedDeque class.

  • Line 4: We create a ConcurrentLinkedDeque object with the name deque.

  • Lines 5–7: We use the add() method of the deque object to add three elements ("1","2","3") to the deque.

  • Line 10: We use the peekLast() method of the deque object to get the last element of the deque. In this case, 3 will be returned.