What is the TreeMap.firstKey() method in Java?

In this shot, we will learn how to use the TreeMap.firstKey() method in Java.

Introduction

The TreeMap.firstKey() method is present in the TreeMap class inside the java.util package. The TreeMap.firstKey() is used to obtain the least key currently present in the map.

Syntax

The syntax of the TreeMap.firstKey() method is given below:

public K firstKey()

Parameter

The TreeMap.firstKey() does not accept any parameters.

Return

The TreeMap.firstKey() method returns one value:

  • Key: It returns the least key currently in the map.

Code

Let’s have a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();
t1.put(1, "Let's");
t1.put(5, "see");
t1.put(2, "TreeMap class");
t1.put(27, "methods");
t1.put(9, "in java.");
System.out.println("The least key in the map is: " + t1.firstKey());
TreeMap<String, Integer> t2 = new TreeMap<String, Integer>();
t2.put("ab", 5);
t2.put("baa", 1);
t2.put("cbc", 2);
t2.put("d", 27);
t2.put("e", 9);
System.out.println("The least key in the map is: " + t2.firstKey());
}
}

Explanation

  • Line 1: We import the required package.

  • Line 2: We make a Main class.

  • Line 4: We make a main() function.

  • Line 6: We declare a TreeMap consisting of keys of type Integer and values of type String.

  • Lines 8 to 12: We insert values in the TreeMap by using the TreeMap.put() method.

  • Line 14: We use TreeMap.firstKey() method and displayed the lowest key present in the TreeMap with a message.

  • Lines 17 to 26: We create another TreeMap object which contains keys of type String and the values of type Integer. Then, we can see in the output that the lowest key would be considered based on the alphabetic order in the case of strings.

So, this is the way to use the TreeMap.firstKey() method in Java.

Free Resources