Java中的 TreeMap floorEntry() 方法及示例
Java.util.TreeMap。 floorEntry() 方法用于返回与小于或等于给定键的最大键关联的键值映射,如果没有这样的键,则返回 null。
句法:
tree_map.floorEntry(K key)
参数:此方法在映射时采用一个参数键进行匹配。
返回值:该方法返回最大键小于或等于键的条目,如果没有这样的键,则返回 null。
例外:
- ClassCastException :如果指定的键无法与映射中当前的键进行比较,则会引发此异常。
- NullPointerException :如果指定的键为空并且此映射使用自然排序,或者其比较器不允许空键,则抛出此异常。
示例 1:当有钥匙时
Java
// Java program to illustrate
// TreeMap floorEntry() method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating an empty TreeMap
TreeMap treemap
= new TreeMap();
// Mapping string values to int keys
treemap.put(20, "Twenty");
treemap.put(10, "Ten");
treemap.put(13, "Thirteen");
treemap.put(60, "Sixty");
treemap.put(50, "Fifty");
System.out.println("The greatest key-value less than 18 is : "
+ treemap.floorEntry(18));
}
}
Java
// Java program to illustrate
// TreeMap floorEntry() method
import java.util.TreeMap;
public class GFG {
public static void main(String args[])
{
// Creating an empty TreeMap
TreeMap treemap
= new TreeMap();
// Mapping string values to int keys
treemap.put(10, "Akash");
treemap.put(20, "Pratik");
treemap.put(30, "Vaibhav");
treemap.put(40, "Sagar");
treemap.put(50, "Abhishek");
// Printing floor entry
System.out.println("The greatest key-value less than 5 is : "
+ treemap.floorEntry(5));
}
}
输出
The greatest key-value less than 18 is : 13=Thirteen
示例 2:当没有这样的密钥时
Java
// Java program to illustrate
// TreeMap floorEntry() method
import java.util.TreeMap;
public class GFG {
public static void main(String args[])
{
// Creating an empty TreeMap
TreeMap treemap
= new TreeMap();
// Mapping string values to int keys
treemap.put(10, "Akash");
treemap.put(20, "Pratik");
treemap.put(30, "Vaibhav");
treemap.put(40, "Sagar");
treemap.put(50, "Abhishek");
// Printing floor entry
System.out.println("The greatest key-value less than 5 is : "
+ treemap.floorEntry(5));
}
}
输出
The greatest key-value less than 5 is : null