Write a Java program to remove and get a key-value mapping associated with the greatest key in this map


This program demonstrates the use of pollLastEntry() method of TreeMap class to remove and get the last (highest) key-value pair from the TreeMap. Here's what the program does:

  • Creates a new TreeMap object s1 with Integer keys and String values.
  • Adds several key-value pairs to the s1 TreeMap using the put() method.
  • Prints the TreeMap s1 using println() method.
  • Calls pollLastEntry() method on s1 which returns and removes the last (highest) key-value pair from the TreeMap.
  • Prints the returned key-value pair from pollLastEntry() method using println() method.
  • Prints the TreeMap s1 again after calling pollLastEntry() method to show that the key-value pair has been removed from the TreeMap.

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class RemoveGet
{  
	public static void main(String args[])
	{
		TreeMap<Integer,String> s1 = new TreeMap<Integer,String>();		
		s1.put(101, "John");
		s1.put(102, "Charles");
		s1.put(103, "Joes");
		s1.put(104, "George");
		s1.put(105, "Smith");
		s1.put(106, "Abi");
 
		System.out.println("Value Before poll : " + s1);
		System.out.println("Value Returned : " + s1.pollLastEntry());
		System.out.println("Value After poll : " + s1);
	}
}

Output

Value Before poll : {101=John, 102=Charles, 103=Joes, 104=George, 105=Smith, 106=Abi}
Value Returned : 106=Abi
Value After poll : {101=John, 102=Charles, 103=Joes, 104=George, 105=Smith}

Example Programs