Java中NavigableMap ceilingKey()方法
Java中NavigableMap接口的ceilingKey()方法用于返回大于或等于给定键的最小键,如果不存在这样的键,则返回null。
语法 :
K ceilingKey(K key)
其中,K是此Map容器维护的键的类型。
参数 : 接受单个参数键Key,它是要映射的键,并且是此集合接受的键的类型。
返回值 : 返回大于或等于给定键的最小键,如果不存在这样的键,则返回null。
下面的程序说明了Java中的ceilingKey()方法:
程序1 : 当key为整数时。
// Java code to demonstrate the working of
// ceilingKey() method
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// 声明一个NavigableMap,其键为整数,其值为字符串
NavigableMap<Integer, String> tmmp = new TreeMap<>();
// 使用put()在NavigableMap中分配值
tmmp.put(2, "two");
tmmp.put(7, "seven");
tmmp.put(3, "three");
// 使用ceilingKey()
// 返回7(下一个更大的键)
System.out.println("6的下一个更大的键是:"
+ tmmp.ceilingKey(6));
// 返回"null",因为不存在大于或等于该数字的值
System.out.println("3的下一个更大的键是:"
+ tmmp.ceilingKey(3));
}
}
6的下一个更大的键是:7
3的下一个更大的键是:3
程序2 : 当key为字符串时。
// Java code to demonstrate the working of
// ceilingKey() method
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// 声明一个NavigableMap,其键为字符串,其值为字符串
NavigableMap<String, String> tmmp = new TreeMap<>();
// 使用put()在NavigableMap中分配值
tmmp.put("one", "two");
tmmp.put("six", "seven");
tmmp.put("two", "three");
// 使用ceilingKey()
// 返回7(下一个更大的键)
System.out.println("five的下一个更大的键是:"
+ tmmp.ceilingKey("five"));
// 返回"null",因为不存在大于或等于该数字的值
System.out.println("six的下一个更大的键是:"
+ tmmp.ceilingKey("six"));
}
}
five的下一个更大的键是:one
six的下一个更大的键是:six
参考 : https://docs.oracle.com/javase/10/docs/api/java/util/NavigableMap.html#ceilingKey(K)
极客教程