SortedMap firstKey() method in Java

The firstKey() method of SortedMap interface in Java is used to return the first or the lowest key currently in this map.

Syntax:

K firstKey()

Where, K is the type of key maintained by this Set.



Parameters: This function does not accepts any parameter.

Return Value: It returns the first print the lowest key currently in this map

Exception: It throws NoSuchElementException, if this map is empty.

Below programs illustrate the above method:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Java program to demonstrate
// working of SortedMap
import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
        // Create a TreeMap of SortedMap
        SortedMap<Integer, String> mp = new TreeMap<>();
  
        // Adding Element to SortedSet
        mp.put(1, "One");
        mp.put(5, "Five");
        mp.put(2, "Two");
        mp.put(3, "Three");
        mp.put(9, "Nine");
  
        // Returning the first key element
        // from the map
        System.out.print("First Key in the map : "
                         + mp.firstKey());
    }
}

chevron_right


Output:

First Key in the map : 1

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Java program to demonstrate
// working of SortedSet
import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
        // Create a TreeSet and inserting elements
        SortedMap<String, String> mp = new TreeMap<>();
  
        // Adding Element to SortedSet
        mp.put("One", "Geeks");
        mp.put("Two", "For");
        mp.put("Three", "Geeks");
        mp.put("Four", "Code");
        mp.put("Five", "It");
  
        // Returning the first key
        // from the map
        System.out.print("First Key in the map is : "
                         + mp.firstKey());
    }
}

chevron_right


Output:

First Key in the map is : Five

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/SortedMap.html#firstKey()



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai