Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
deque
communitycreator

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

Sumit Sharma

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.

In this shot, we will discuss how to use Deque.peekFirst() method, which is present in the Deque interface inside the java.util package.

The Deque.peekFirst() method is used to retrieve or to get the head element of the given Deque. This method doesn’t delete or remove the head element from the Deque. If the given Deque is empty, then this method returns null.

Syntax

Deque.peekFirst();

Parameter

The Deque.peekFirst() method doesn’t take any parameter.

Return

The Deque.peekFirst() method returns the first element of deque.

It returns null if the Deque is empty.

Code

Let’s take a look at the below code snippet.

import java.util.Deque;
import java.util.ArrayDeque;
class Solution {
public static void main(String[] args) {
Deque<Integer> objDeque = new ArrayDeque<>();
objDeque.add(10);
objDeque.add(20);
objDeque.add(30);
objDeque.add(40);
objDeque.add(50);
System.out.println("The elements of deque are:-\n" + objDeque);
int element = objDeque.peekFirst();
System.out.println("First element of deque is: " + element);
System.out.println("Deque after peekfirst operation is:-\n" + objDeque);
}
}
Using Deque.peekFirst() method in Java

Explanation

  • In lines 1 to 2, we imported the Deque and ArrayDeque interfaces from the java.util. package.
  • From lines 6 to 12, we initialized the object of Deque of Integer type with ArrayDeque and added elements 10, 20, 30, 40, 50 in that.
  • In line 14, we printed the elements of Deque by implicitly calling toString().
  • In line 16, we used the method deque.peekFirst() and stored the returned element in the element variable.
  • In line 18, we printed the head of the Deque.
  • In line 19, we printed the Deque after using the peekFirst() method by implicitly calling toString().

In this way, we can use the Deque.peekFirst() method in Java.

RELATED TAGS

java
deque
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