Java SortedMap firstKey()方法

Java SortedMap firstKey()方法

Java中SortedMap接口 的firstKey()方法用于返回当前该地图中的第一个或最低的键。

语法:

K firstKey()

其中,K是这个Set所维护的键的类型。

参数 :该函数不接受任何参数。

返回值 :它返回当前在这个地图中的第一个打印的最低键。

异常 :如果这个地图是空的,它会抛出NoSuchElementException。

下面的程序说明了上述方法。

程序1 :

// 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());
    }
}

输出。

First Key in the map : 1

示例2 :

// 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());
    }
}

输出。

First Key in the map is : Five

参考资料 : https://docs.oracle.com/javase/10/docs/api/java/util/SortedMap.html#firstKey()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程