TreeMap pollLastEntry() method in java

Let’s learn TreeMap pollLastEntry() method in java.

TreeMap pollLastEntry() method in java

pollLastEntry() method of TreeMap class removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

Syntax:

public Map.Entry<K, V> pollLastEntry()

Returns:

the removed last entry of this map, or null if this map is empty.

Now let’s see example on TreeMap pollLastEntry() method.

import java.util.TreeMap;
public class TreeMapPollLastEntryMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(63, "yellow");
      tm.put(95, "red");
      tm.put(96, "green");
      tm.put(21, "violet");
      tm.put(28, "blue");
      System.out.println("TreeMap before using pollLastEntry() method: " + tm);
      System.out.println("Value is: " + tm.pollLastEntry());
      System.out.println("TreeMap after using pollLastEntry() method: " + tm);
   }
}

Output:

TreeMap before using pollLastEntry() method: {21=violet, 28=blue, 63=yellow, 95=red, 96=green}
Value is: 96=green
TreeMap after using pollLastEntry() method: {21=violet, 28=blue, 63=yellow, 95=red}


Also read – Quicksort java