Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

ConcurrentLinkedDeque is a thread-safe, unbounded deque. The null value is not permitted as an element. We can use the ConcurrentLinkedDeque when multiple threads share a single deque.

The peekFirst method can be used to get the first element of the ConcurrentLinkedDeque object.

Syntax

The syntax of the peekFirst() method is as follows:


public E peekFirst()

Parameters

This method doesn’t take an argument.

Return value

The peekFirst method retrieves the first element of the deque object. If the deque is empty, then the method returns null.

This method is similar to the getFirst method, except that the peekFirst method returns null if the deque is empty, whereas the getFirst method throws the NoSuchElementException.

Code

The code below demonstrates how to use the peekFirst method.

import java.util.concurrent.ConcurrentLinkedDeque;
class PeekFirst {
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.peekFirst() returns : " + deque.peekFirst());
}
}

Explanation

  • Line 1: We import the ConcurrentLinkedDeque class.

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

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

  • Line 10: We use the peekFirst() method of the deque object to get the first element of the deque. In our case, 1 will be returned.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring