java.util.TreeMap.subMap()


描述

subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)方法用来返回此映射,其键范围从fromKey到toKey的所述部分的视图。如果fromKey和toKey相等,则返回的映射为空,除非fromExclusive和toEx​​clusive都为真。返回的地图由此地图支持,因此返回的地图中的更改将反映在此地图中,反之亦然。

声明

以下是java.util.TreeMap.subMap()方法的声明。

public NavigableMap<K,V> subMap(K fromKey,
                                boolean fromInclusive,
                                K toKey,
                                boolean toInclusive)

参数

fromKey - 这是返回映射中键的低端点。

fromInclusive - 如果要将低端点包含在返回的视图中,则为true。

toKey - 这是返回映射中键的高端点。

toInclusive - 如果要将高端点包含在返回的视图中,则为true。

返回值

方法调用返回此映射部分的视图,其键的范围从fromKey到toKey。

异常

ClassCastException - 如果使用此映射的比较器无法将fromKey和toKey相互比较,则抛出异常。

NullPointerException - 如果fromKey或toKey为null并且此映射使用自然排序,或者其比较器不允许空键,则抛出此异常。

IllegalArgumentException - 如果fromKey大于toKey,则抛出此异常; 或者如果此地图本身具有受限范围,则fromKey或toKey位于范围的边界之外。

实例

以下示例显示了java.util.TreeMap.subMap()的用法

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>();
      NavigableMap<Integer, String> treemapincl = 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");      

      System.out.println("Getting a portion of the map");
      treemapincl = treemap.subMap(1, true, 3, true);
      System.out.println("Sub map values: "+treemapincl);      
   }    
}

让我们编译并运行上面的程序,这将产生以下结果。

Getting a portion of the map
Sub map values: {1=one, 2=two, 3=three}