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

Overview

The Deque.peekLast() method is present in the Deque interface inside the java.util package. It is used to retrieve or fetch the last element of the given deque, but it does not remove the last element of the given deque. If the given deque is empty, then this method will return null.

Syntax

Let’s view the syntax of the function.

Deque.PeekLast();

Parameter

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

Return

The Deque.peekLast() method returns the last element of the deque, and it returns null if the deque is empty.

Code

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

import java.util.*;
class Solution3 {
public static void main(String[] args) {
Deque<Integer> dq= new ArrayDeque<>();
dq.add(10);
dq.add(20);
dq.add(30);
dq.add(40);
dq.add(50);
System.out.println("the elements of deque are:-\n"+dq);
int ele= dq.peekLast();
System.out.println("the first element of deque is:-\n"+ ele);
System.out.println("deque after peekLast operation is:-\n"+ dq);
}
}

Explanation

  • In line 1, we imported the java.util.* package to include the Deque interface.
  • From line 7 to 17, we initialized the object of the deque of Integer type and added elements 10,20,30,40,50 in that.
  • In line 19, we printed the elements of the deque.
  • In line 21, we used the method deque.peekLast() and stored the returned element in the ele variable.
  • In line 23, we printed the last element of deque.
  • In line 25, we printed the deque after using the peekLast() method.

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

Free Resources