SortedMap<K,V> headMap(K toKey)
描述 (Description)
headMap(K toKey)方法用于返回此映射部分的视图,其键的严格小于toKey。
声明 (Declaration)
以下是java.util.TreeMap.headMap()方法的声明。
public SortedMap<K,V> headMap(K toKey)
参数 (Parameters)
toKey - 这是返回映射中键的高端点(独占)。
返回值 (Return Value)
方法调用返回此映射部分的视图,其键的严格小于toKey。
异常 (Exception)
ClassCastException - 如果toKey与此映射的比较器不兼容(或者,如果映射没有比较器,如果toKey未实现Comparable),则抛出此异常。 如果toKey无法与映射中当前的键进行比较,则实现可能(但不是必须)抛出此异常。
NullPointerException - 如果toKey为null并且此映射使用自然排序,或者其比较器不允许空键,则抛出此异常。
IllegalArgumentException - 如果此映射本身具有受限范围,并且toKey位于范围的边界之外,则抛出此异常。
例子 (Example)
以下示例显示了java.util.TreeMap.headMap()方法的用法。
package com.iowiki;
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}