Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the TreeMap.pollLastEntry() method in Java?

Harsh Jain

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 learn how to use the TreeMap.pollLastEntry() method in Java.

Introduction

The TreeMap.pollLastEntry() method is present in the NavigableSet interface inside the java.util package. The TreeMap class implements the NavigableSet interface.

TreeMap.pollLastEntry() is used to retrieve and remove the key-value pair, where the key is the highest key present in the map.

Syntax

The syntax of the TreeMap.pollLastEntry() method is shown below:

Map.entry<K,V> pollLastEntry();
Java syntax for pollLastEntry

Parameters

TreeMap.pollLastEntry() does not accept any parameters.

Return value

The TreeMap.pollFirstEntry() method returns the key-value pair with the highest value of key from the map.

Code

Let’s have a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();
t1.put(1, "Learn");
t1.put(5, "in-demand");
t1.put(2, "tech skills");
t1.put(27, "on");
t1.put(9, "Educative.io");
System.out.println("The removed element from the TreeMap" +
"after using pollLastEntry() is: " + t1.pollLastEntry());
}
}
Using the TreeMap.pollLastEntry() method in Java

Explanation

  • In line 1, we import the required package.

  • In line 2, we make a Main class.

  • In line 4, we make a main() function.

  • In line 6, we declare a TreeMap that consists of keys of type Integer and values of type String.

  • From lines 8 to 12, we use the TreeMap.put() method to insert values in the TreeMap.

  • In line 14, we use the TreeMap.pollLastEntry() method and display the removed key-value value from the map with a message.

RELATED TAGS

java
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