Java TreeSet headSet()方法

java.util.TreeSet.headSet(E toElement,boolean inclusive) 方法用于返回小于或等于(如果包含,则为true)指定元素的元素组。

1 语法

public NavigableSet<E> headSet(E toElement,boolean inclusive)

2 参数

toElement:这是返回集的最大边界值。

inclusive:如果要在返回的视图中最大边界值,则为true。

3 返回值

返回此集合中元素小于(或等于,如果包含在内,则为true)toElement的部分的视图。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.TreeSet.headSet(E toElement,boolean inclusive)方法的例子
 */
import java.util.Iterator;
import java.util.TreeSet;

public class Demo {
    public static void main(String[] args) {

        // creating TreeSet
        TreeSet <Integer>tree = new TreeSet<Integer>();
        TreeSet <Integer>treeheadsetincl = new TreeSet<Integer>();

        // adding in the tree
        tree.add(12);
        tree.add(13);
        tree.add(14);
        tree.add(15);
        tree.add(16);
        tree.add(17);

        // getting values for 15 inclusive true
        treeheadsetincl = (TreeSet)tree.headSet(15, true);

        // creating iterator
        Iterator iterator;
        iterator = treeheadsetincl.iterator();

        //Displaying the tree set data
        System.out.println("Tree set data for '15' inclusive TRUE: ");

        while (iterator.hasNext()) {
            System.out.println(iterator.next() + " ");
        }

        // getting values for 15 inclusive false
        treeheadsetincl = (TreeSet)tree.headSet(15, false);

        // creating iterator
        iterator = treeheadsetincl.iterator();

        //Displaying the tree set data
        System.out.println("Tree set data for '15' inclusive FALSE: ");

        while (iterator.hasNext()) {
            System.out.println(iterator.next() + " ");
        }
    }
}

输出结果为:

Tree set data for '15' inclusive TRUE: 
12 
13 
14 
15 
Tree set data for '15' inclusive FALSE: 
12 
13 
14

热门文章

优秀文章