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.
Deque.peekFirst();
The Deque.peekFirst() method doesn’t take any parameter.
The Deque.peekFirst() method returns the first element of deque.
It returns null if the Deque is empty.
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);}}
Deque and ArrayDeque interfaces from the java.util. package.Deque of Integer type with ArrayDeque and added elements 10, 20, 30, 40, 50 in that.Deque by implicitly calling toString().deque.peekFirst() and stored the returned element in the element variable.Deque.Deque after using the peekFirst() method by implicitly calling toString().In this way, we can use the Deque.peekFirst() method in Java.