Java 中的 NavigableMap headMap()
Java 中 NavigableMap 接口的 headMap() 方法用于返回该映射的部分视图,其键小于(如果 inclusive 为 true,则小于等于)toKey。
- 返回的映射由该映射支持,因此返回映射中的更改会反映在该映射中,反之亦然。
- 返回的映射支持该映射支持的所有可选映射操作。
- 在尝试插入键超出其范围的情况下,返回的映射将抛出 IllegalArgumentException。
语法 :
NavigableMap<K, V> headMap(K toKey,
boolean inclusive)
其中,K 是该映射维护的键类型,V 是映射中键相关联的值。
参数 : 此函数接受两个参数:
- toKey : 此参数指的是键。
- inclusive : 此参数决定是否应将要删除的键与等式进行比较。
返回值 : 返回一个视图,该视图的部分键小于(如果 inclusive 为 true,则小于等于)toKey。
示例 1 : 当键为整数且第二个参数缺失时。
// Java code to demonstrate the working of
// headMap?() method
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// 声明一个 Integer 和 String 的 NavigableMap
NavigableMap<Integer, String> nmmp = new TreeMap<>();
// 使用 put() 在 NavigableMap 中分配值
nmmp.put(2, "two");
nmmp.put(7, "seven");
nmmp.put(3, "three");
System.out.println("键小于或等于 7 的映射 : " + nmmp.headMap(7));
}
}
键小于或等于 7 的映射 : {2=two, 3=three}
示例 2 : 第二个参数已指定时。
// Java code to demonstrate the working of
// headMap?() method
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// 声明一个 Integer 和 String 的 NavigableMap
NavigableMap<Integer, String> nmmp = new TreeMap<>();
// 使用 put() 在 NavigableMap 中分配值
nmmp.put(2, "two");
nmmp.put(7, "seven");
nmmp.put(3, "three");
nmmp.put(9, "nine");
// 将第二个参数设置为 true 的 headMap
System.out.println("键小于或等于 7 的映射 : " + nmmp.headMap(7, true));
}
}
键小于或等于 7 的映射 : {2=two, 3=three, 7=seven}
参考资料 : https://docs.oracle.com/javase/10/docs/api/java/util/NavigableMap.html#headMap(K, boolean)
极客教程