Java.util.TreeMap 类

java.util.TreeMap.firstKey() 方法返回此映射中当前的第一个(最低)键。

语法

public K firstKey()

这里,K 是容器维护的密钥类型。

参数

不需要参数。

返回值

返回当前在此映射中的第一个(最低)键。

异常

抛出NoSuchElementException,如果此映射为空。

示例:

在下面的示例中,java.util.TreeMap.firstKey () 方法返回给定映射中的第一个(最低)键。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建树形图
    TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //填充map
    MyMap.put(102, "John");
    MyMap.put(103, "Marry");
    MyMap.put(101, "Kim");
    MyMap.put(104, "Jo");
    MyMap.put(105, "Sam");

    //打印map
    System.out.println("MyMap contains: " + MyMap); 

    //打印map中的第一个键
    System.out.println("The first key in the map is: " + MyMap.firstKey());     
  }
}

上述代码的输出将是:

MyMap contains: {101=Kim, 102=John, 103=Marry, 104=Jo, 105=Sam}
The first key in the map is: 101