Java NavigableMap headMap()
Java中NavigableMap接口的headMap()方法用于返回该地图中键值小于(或等于,如果包容性为真)toKey部分的视图。
- 返回的地图是由这个地图支持的,所以返回的地图的变化会反映在这个地图上,反之亦然。
- 返回的地图支持该地图支持的所有可选的地图操作。
- 当试图插入一个超出其范围的键时,返回的地图将抛出一个IllegalArgumentException。
语法:
NavigableMap<K, V> headMap(K toKey,
boolean inclusive)
其中,K是这个地图所维护的键的类型,V是地图中与键相关的值。
参数 :该函数接受两个参数。
- toKey : 这个参数指的是键。
- inclusive : 这个参数决定要删除的键是否要进行平等比较。
返回值 : 它返回该地图中键值小于(或等于,如果包容性为真)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)
{
// Declaring the NavigableMap of Integer and String
NavigableMap<Integer, String> nmmp = new TreeMap<>();
// assigning the values in the NavigableMap
// using put()
nmmp.put(2, "two");
nmmp.put(7, "seven");
nmmp.put(3, "three");
System.out.println("View of map with key less than"
+ " or equal to 7 : " + nmmp.headMap(7));
}
}
输出:
View of map with key less than or equal to 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)
{
// Declaring the NavigableMap of Integer and String
NavigableMap<Integer, String> nmmp = new TreeMap<>();
// assigning the values in the NavigableMap
// using put()
nmmp.put(2, "two");
nmmp.put(7, "seven");
nmmp.put(3, "three");
nmmp.put(9, "nine");
// headMap with second argument as true
System.out.println("View of map with key less than"
+ " or equal to 7 : " + nmmp.headMap(7, true));
}
}
输出:
View of map with key less than or equal to 7 : {2=two, 3=three, 7=seven}
参考资料 : https://docs.oracle.com/javase/10/docs/api/java/util/NavigableMap.html#headMap(K, boolean)