TreeMap in Java is a part of the Java Collections Framework and implements the NavigableMap interface. It stores elements in a sorted order of keys, either according to the natural ordering of keys. To access the lowest (first) key in a TreeMap, Java provides two closely related methods:
firstEntry() Method
The firstEntry() method returns the key–value pair associated with the lowest key in the TreeMap.
- If the map is empty, it returns null
- It is useful when you need both the key and its mapped value.
import java.util.*;
public class GFG {
public static void main(String[] args) {
TreeMap<Integer, String> treemap = new TreeMap<>();
treemap.put(2, "two");
treemap.put(7, "seven");
treemap.put(3, "three");
treemap.put(1, "one");
treemap.put(6, "six");
treemap.put(9, "nine");
System.out.println("Lowest entry is: " + treemap.firstEntry());
}
}
Output
Lowest entry is: 1=one
Explanation:
- The TreeMap automatically sorts all keys in ascending order.
- After inserting all entries, the smallest key in the map is 1.
- The firstEntry() method retrieves the complete key–value pair associated with this key.
- Therefore, the output is displayed as 1=one.
Syntax
public Map.Entry<K, V> firstEntry()
Return Type:
- Map.Entry<K, V> containing the least key and its value
- null if the map is empty
firstKey() Method
The firstKey() method returns only the lowest key currently present in the TreeMap.
- It does not return the value
- If the map is empty, it throws a NoSuchElementException
import java.util.*;
class GFG {
public static void main(String[] args) {
TreeMap<Integer, String> treemap = new TreeMap<>();
treemap.put(2, "two");
treemap.put(1, "one");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(5, "five");
treemap.put(9, "nine");
System.out.println("Lowest key is: " + treemap.firstKey());
}
}
Output
Lowest key is: 1
Explanation:
- Keys are automatically sorted in ascending order.
- firstKey() returns the smallest key without its value.
- If the map is empty, an exception is thrown instead of returning null.
Syntax
public K firstKey()
Return Type: The first (lowest) key currently in this map.
firstEntry() vs firstKey()
| Feature | firstEntry() | firstKey() |
|---|---|---|
| Return type | Returns a Map.Entry<K, V> | Returns only the key K |
| Value access | Provides both key and value | Provides only the key |
| Empty map behavior | Returns null if the map is empty | Throws NoSuchElementException if empty |
| Safety | Safer when map may be empty | Risky without empty check |
| Typical use | Used when key–value pair is needed | Used when only the key is required |