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

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

SortedMap.firstKey() method are present in the SortedMap interface inside the java.util package.

The SortedMap.firstKey() method is used to obtain the lowest key-element present in the SortedMap.

Parameter

The SortedMap.firstKey() method doesn’t take any parameter.

Return value

The SortedMap.firstKey() method returns:

  • Key: Lowest key present in the SortedMap.

Code

Let us look at the below code snippet:

import java.util.*;
class Main
{
public static void main(String[] args)
{
// creating a TreeMap of SortedMap
SortedMap<Integer, String> s = new TreeMap<Integer,String>();
// inserting elements in the SortedMap
s.put(2,"Welcome");
s.put(12,"to");
s.put(31,"the");
s.put(18,"world");
s.put(25,"of");
s.put(36,"java");
// displaying the whole map
System.out.println("SortedMap mappings are: "+ s);
// displaying the first key element in the map
System.out.println("The first key in the SortedMap is: " + s.firstKey());
}
}

Explanation

  • In line 1, we imported the required package.
  • In line 2, we made a Main class.
  • In line 4, we made a main function.
  • In line 7, we declared a SortedMap consisting of Integer type keys and String type values.
  • From lines 10 to 15, we inserted values in the Hashtable by using the TreeMap.put() method.
  • In line 18, we displayed the mappings of the present in the SortedMap.
  • In line 21, we used the SortedMap.firstKey() method to obtain the lowest key of SortedMap and displayed it.

In this way, we can use SortedMap.firstKey() method in Java.

Free Resources