In this shot, we will learn how to use the TreeMap.pollFirstEntry() method in Java.
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.
The syntax of the TreeMap.pollFirstEntry() method is shown below:
Map.entry<K,V> pollFirstEntry();
TreeMap.pollFirstEntry() does not accept any parameters.
The TreeMap.pollFirstEntry() method returns the key-value pair with the smallest key value from the map.
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());}}
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.pollFirstEntry() method and display the removed key-value value from the map with a message.