Java TreeMap - pollFirstEntry() Method
The java.util.TreeMap.pollFirstEntry() method is used to remove and return a key-value mapping associated with the least key in this map, or null if the map is empty.
Syntax
public Map.Entry<K,V> pollFirstEntry()
Here, K and V are the type of key and value respectively maintained by the container.
Parameters
No parameter is required.
Return Value
Returns the removed first entry of this map, or null if this map is empty.
Exception
NA.
Example:
In the example below, the java.util.TreeMap.pollFirstEntry() method is used to remove the key-value mapping associated with the least key in the given map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treemap TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>(); //populating the map MyMap.put(102, "John"); MyMap.put(103, "Marry"); MyMap.put(101, "Kim"); MyMap.put(104, "Jo"); MyMap.put(105, "Sam"); //printing the map System.out.println("MyMap contains: " + MyMap); //removing the first entry from the map MyMap.pollFirstEntry(); //printing the map System.out.println("MyMap contains: " + MyMap); } }
The output of the above code will be:
MyMap contains: {101=Kim, 102=John, 103=Marry, 104=Jo, 105=Sam} MyMap contains: {102=John, 103=Marry, 104=Jo, 105=Sam}
❮ Java.util - TreeMap