TreeMap firstEntry() and firstKey() Methods in Java with Examples

Last Updated : 24 Jan, 2026

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.
Java
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
Java
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()

FeaturefirstEntry()firstKey()
Return typeReturns a Map.Entry<K, V>Returns only the key K
Value accessProvides both key and valueProvides only the key
Empty map behaviorReturns null if the map is emptyThrows NoSuchElementException if empty
SafetySafer when map may be emptyRisky without empty check
Typical useUsed when key–value pair is neededUsed when only the key is required
Comment