What is the Deque.peek() method in Java?
Overview
In this shot, we will discuss how to use the Deque.peek() method in Java.
The Deque.peek() method is present in the Deque interface inside the java.util package.
Deque.peek() is used to get the element at the head of the deque.
Syntax
Deque.peek()
Parameters
The Deque.peek() method doesn’t take any parameters.
Return value
Element: The element at the head of the deque.
Code
Let us look at the code snippet below.
import java.util.*;class Main{public static void main(String[] args){Deque<Integer> d = new LinkedList<Integer>();d.add(2);d.add(28);d.add(6);d.add(80);d.add(21);d.add(7);d.add(15);System.out.println("The peek element of the deque is: "+d.peek());}}
Explanation
-
In line 1, we import the required package.
-
In line 2, we make a
mainclass. -
In line 4, we make a
mainfunction. -
In line 6, we declare a
dequethat consists ofIntegertype elements. -
From lines 8-14, we use the
Deque.add()method to insert the elements in thedeque. -
In line 16, we use the
Deque.peek()method to display the element at the head ofDeque.
In this way, we can use the Deque.peek() method in Java.