Site icon JavaGoal

lastEntry() method

lastEntry(): It returns the key-value pair having the greatest key (Key having highest value). It returns the pair that associated with greatest key. It returns null if TreeMap is empty.

import java.util.TreeMap;
class ExampleOfTreeMap
{
	public static void main(String arg[])
	{
		TreeMap<Integer, String> listOfNames = new TreeMap<Integer, String>();
		listOfNames.put(3, "C");
		listOfNames.put(1, "A");
		listOfNames.put(2, "D");
		listOfNames.put(6, "B");
		listOfNames.put(8, "B");
		
		// It return the Pair of Key and value of greatest Key of TreeMap
		System.out.println("Pair of least Key :"+listOfNames.lastEntry());
	
	}
}

Output: Pair of least Key :8=B

Exit mobile version