Java TreeMap.firstKey() example

In this java tutorial, You will learn how get first key element of TreeMap class.This method returns the first (lowest) key currently in this map.

Returns the first (lowest) key currently in this map.


public K firstKey()


The first (lowest) key currently in this map.


NoSuchElementException - if this map is empty.

Java TreeMap firstKey() example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap e.g. students.put(1, "Pooja");
  • Print the TreeMap values.
  • students.firstKey(); It will return the first key of TreeMap.
package com.technicalkeeda;

import java.util.TreeMap;

public class App {
    public static void main(String args[]) {

        TreeMap < Integer, String > students = new TreeMap < Integer, String > ();

        students.put(1, "Pooja");
        students.put(2, "Ajit");
        students.put(3, "Yashwant");
        students.put(4, "Aditi");

        System.out.println("TreeMap values :- " + students);

        System.out.println("First Key of the map set:-" + students.firstKey());



TreeMap values :- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi}
First Key of the map set:-1