Java TreeMap.firstKey() example

Java TreeMap.firstKey() example

By technicalkeeda, Views 309, Date 22-Feb-2018

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.

tags Java

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


Hi there! I am founder of and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][]