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 SortedMapSortedMap<Integer, String> s = new TreeMap<Integer,String>();// inserting elements in the SortedMaps.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 mapSystem.out.println("SortedMap mappings are: "+ s);// displaying the first key element in the mapSystem.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
Mainclass. - In line 4, we made a
mainfunction. - In line 7, we declared a
SortedMapconsisting 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 ofSortedMapand displayed it.
In this way, we can use SortedMap.firstKey() method in Java.