Java TreeMap.firstEntry() example

In this java tutorial, You will learn how to use firstEntry() method of TreeMap class.The firstEntry() method is used to return a key-value mapping associated with the least key in this map, or null if the map is empty.

Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

syntax

public Map.Entry<K,V> firstEntry()

Returns

An entry with the least key, or null if this map is empty.

Java TreeMap firstEntry() example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap e.g. students.put(1, "Pooja");
  • Print the TreeMap values.
  • students.firstEntry(); It will return first entry of TreeMap.
  • Print the first entry 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 entry:- " + students.firstEntry());

    }
}

output

TreeMap values:- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi}
First entry:- 1=Pooja