What is the TreeMap.pollFirstEntry() method in Java?
In this shot, we will learn how to use the TreeMap.pollFirstEntry() method in Java.
Introduction
The TreeMap.pollFirstEntry() method is present in the NavigableSet interface inside the java.util package. The TreeMap class implements the NavigableSet interface.
TreeMap.pollFirstEntry() is used to retrieve and remove the key-value pair, where the key is the lowest key present in the map.
Syntax
The syntax of the TreeMap.pollFirstEntry() method is shown below:
Map.entry<K,V> pollFirstEntry();
Parameters
TreeMap.pollFirstEntry() does not accept any parameters.
Return value
The TreeMap.pollFirstEntry() method returns the key-value pair with the smallest key value 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 pollFirstEntry() is: " + t1.pollFirstEntry());}}
Explanation
-
In line 1, we import the required package.
-
In line 2, we make a
Mainclass. -
In line 4, we make a
main()function. -
In line 6, we declare a
TreeMapthat consists of keys of typeIntegerand values of typeString. -
From lines 8 to 12, we use the
TreeMap.put()method to insert values in theTreeMap. -
In line 14, we use the
TreeMap.pollFirstEntry()method and display the removed key-value value from the map with a message.