TreeMap firstKey() in Java

firstKey(): This method is available in java.util.TreeMap class of Java.

Syntax:

Integer java.util.TreeMap.firstKey()

This method returns the first (lowest) key currently on this map.

Parameters: NA

Returns: the first (lowest) key currently on this map.

Throws:

NoSuchElementException - if this map is empty

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMapfirstKey {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        System.out.println(treeMap.firstKey());
    }
}

Output:

2


Approach 2: NoSuchElementException

Java

import java.util.TreeMap;

public class TreeMapfirstKey {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        System.out.println(treeMap.firstKey());
    }
}

Output:

Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.TreeMap.key(TreeMap.java:1596) at java.base/java.util.TreeMap.firstKey(TreeMap.java:291)


No comments:

Post a Comment