java.util.TreeMap.headMap() 方法
描述
headMap(K toKey) 方法用于返回此映射部分的视图,其键严格小于 toKey。
声明
以下是 java.util.TreeMap.headMap() 方法的声明。
public SortedMap<K,V> headMap(K toKey)
参数
toKey − 这是返回映射中键的高端(不包括)。
返回值
该方法调用返回此映射部分的视图,其键严格小于 toKey。
异常
ClassCastException − 如果 toKey 与此映射的比较器不兼容(或者,如果映射没有比较器,如果 toKey 未实现 Comparable),则会引发此异常。 如果 toKey 无法与映射中当前的键进行比较,则实现可以但不是必须抛出此异常。
NullPointerException − 如果 toKey 为 null 并且此映射使用自然排序,或者其比较器不允许 null 键,则会引发此异常。
IllegalArgumentException − 如果此映射本身具有受限范围,并且 toKey 位于范围范围之外,则会引发此异常。
示例
下面的例子展示了 java.util.TreeMap.headMap() 方法的使用。
package com.tutorialspoint;
import java.util.*;
public class TreeMapDemo {
public static void main(String[] args) {
// creating maps
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
SortedMap<Integer, String> treemaphead = new TreeMap<Integer, String>();
// populating tree map
treemap.put(2, "two");
treemap.put(1, "one");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(5, "five");
// getting head map
treemaphead = treemap.headMap(3);
System.out.println("Checking values of the sorted map");
System.out.println("Value is: "+ treemaphead);
}
}
让我们编译并运行上面的程序,这将产生以下结果.
Checking values of the sorted map
Value is: {1=one, 2=two}

