Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is the Deque.peekLast() 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.

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();
Syntax in Jave

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);

    }

}
Using Deque.peekLast() method in Java

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.

RELATED TAGS

communitycreator
java

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