Java TreeMap subMap()方法

java.util.TreeMap.subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) 返回key-value对,其键的范围从fromKey到toKey。

1 语法

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

2 参数

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

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

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

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

3 返回值

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

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.TreeMap.subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)方法的例子
 */
import java.util.*;

public class Demo {
    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}

热门文章

优秀文章