Get the key/value of the first TreeMap element in Java
The code below shows how to retrieve the first key in a TreeMap in Java. To get the first element, you need to call the method. firstKey(), and then you can get the corresponding value.import java.util.Iterator;Executing this code gives:
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",5);
tmap.put("Key2",7);
tmap.put("Key3",2);
tmap.put("Key4",4);
// Get all inputs
Set set = tmap.entrySet();
// Get iterator to browse the list
Iterator itr = set.iterator();
// Show key-value pairs
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.firstEntry();
System.out.println("First key/value element: ");
System.out.println(ent.getKey()+" ==> "+ent.getValue());
}
}
key: Key1 - Value: 5References:
key: Key2 - Value: 7
key: Key3 - Value: 2
key: Key4 - Value: 4
First key/value:
Key1 ==> 5
The firstKey()