Java中SortedMap接口的lastKey()方法用于返回此映射中当前的最后一个或最大键。
用法:
K lastKey()
其中,K是此Set维护的 key 的类型。
参数:此函数不接受任何参数。
返回值:返回当前Map中的最后一个或最大的键
异常:如果此映射为空,则抛出NoSuchElementException。
以下示例程序旨在说明上述方法:
程序1:
// 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 mp = new TreeMap<>();
// Adding Element to SortedSet
mp.put(1, "One");
mp.put(2, "Two");
mp.put(3, "Three");
mp.put(4, "Four");
mp.put(5, "Five");
// Returning the last key from the map
System.out.print("Last Key in the map is : "
+ mp.lastKey());
}
}
输出:
Last Key in the map is : 5
程序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 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 last key from the map
System.out.print("Last Key in the map is : "
+ mp.lastKey());
}
}
输出:
Last Key in the map is : Two