Get the key/value of the last TreeMap element in Java

We saw in the previous article how to get the first element of a TreeMap in Java. This tutorial explains how to retrieve the last key and its value from a TreeMap in Java. To go directly to the last item, you only need to call the lastKey(), and then you can get the corresponding value from the Entry object returned by this method with the method getValue().

import java.util.Iterator; 
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map;

public class TreeMapFirstkey {

public static void main(String a[]){
// Create a TreeMap
TreeMap< String, Integer> tmap = new TreeMap< String, Integer> ();

// Add key-value pairs to TreeMap
tmap.put("Key1",8);
tmap.put("Key2",6);
tmap.put("Key3",11);
tmap.put("Key4",7);

// Get all inputs
Set set = tmap.entrySet();

// Get iterator to browse the list
Iterator itr = set.iterator();

// Show all items in the list
while(itr.hasNext()) {
Map.Entry mentry = (Map.Entry)itr.next();
System.out.print("key: "+mentry.getKey() + " - ");
System.out.println("Value: "+mentry.getValue());
}

Entry< String,Integer> ent = tmap.lastEntry();
System.out.println("Last key/value element: ");
System.out.println(ent.getKey()+" ==> "+ent.getValue());
}
}
Running this code gives:

key: Key1 - Value: 8
key: Key2 - Value: 6
key: Key3 - Value: 11
key: Key4 - Value: 7

First key/value:
Key4 ==> 7
References:
The lastKey()