Java中的SortedMap lastKey()方法
在Java中的SortedMap是Map的一种有序子类,它根据键的自然顺序维护其元素顺序。其中lastKey()方法会返回当前SortedMap中最后一个元素的键。
语法
K lastKey()
参数
无参数
返回值
返回当前SortedMap中最后一个元素的键。如果当前SortedMap为空,则返回null。
示例
import java.util.*;
public class SortedMapDemo {
public static void main(String[] args) {
// Create a sorted map
SortedMap<String, String> sortedMap = new TreeMap<String, String>();
// Add elements to the map
sortedMap.put("1", "One");
sortedMap.put("2", "Two");
sortedMap.put("3", "Three");
sortedMap.put("4", "Four");
sortedMap.put("5", "Five");
// Display the last key
System.out.println("Last Key: " + sortedMap.lastKey());
}
}
上述示例输出结果为:
Last Key: 5
结论
在Java中,使用SortedMap的lastKey()方法可以返回当前SortedMap中最后一个元素的键。该方法在SortedMap中非常有用,能够快速获取最后一个元素的键。了解该方法可以使我们更好地使用SortedMap类。