java.util.TreeMap.subMap() 方法

描述

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


声明

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

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

参数

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

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

  • toKey − 这是返回映射中键的高端。

  • toInclusive − 如果要在返回的视图中包含高端端点,这是正确的。


返回值

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


异常

  • ClassCastException − 如果无法使用此映射的比较器将 fromKey 和 toKey 相互比较,则会引发异常。

  • NullPointerException − 如果 fromKey 或 toKey 为 null 并且此映射使用自然排序,或者其比较器不允许 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}