当前位置: 首页 > 工具软件 > Subset > 使用案例 >

java treeset subset_Java TreeSet subSet()用法及代码示例

林鸿彩
2023-12-01

java.util.TreeSet.subSet()用于返回参数中提到的范围内的现有TreeSet的子集。该方法接受一个上限和一个下限,并返回范围内提到的所有元素。如果元素存在于集合中,则包括下限,而排除上限。本质上,它使子集大于等于下限,并且严格小于上元素。

用法:

TreeSettree_set.subSet(Object low_element, Object up_element)

参数:

low_element:这是TreeSet的类型,它定义了评估子集的下限或起始元素。该元素包含在子集中。

up_element:这是TreeSet的类型,它定义子集要评估的上限或最后一个元素。该元素从子集中排除。

返回值:该方法返回在给定参数范围内提到的TreeSet类型的子集。

以下程序说明了java.util.TreeSet.subSet()方法:

程序1:

// Java code to illustrate subSet() method

import java.io.*;

import java.util.Iterator;

import java.util.TreeSet;

public class Tree_Set_Demo {

public static void main(String[] args)

{

// Creating an empty TreeSet

TreeSet tree_set = new TreeSet();

// Adding the elements using add()

tree_set.add(5);

tree_set.add(1);

tree_set.add(50);

tree_set.add(10);

tree_set.add(20);

tree_set.add(6);

tree_set.add(20);

tree_set.add(18);

tree_set.add(9);

tree_set.add(30);

// Creating the subset tree

TreeSet sub_set = new TreeSet();

// Limiting the values till 5

sub_set = (TreeSet)tree_set.subSet(6, 30);

// Creating an Iterator

Iterator iterate;

iterate = sub_set.iterator();

// Displaying the tree set data

System.out.println("The resultant values within the sub set: ");

// Iterating through the subset

while (iterate.hasNext()) {

System.out.println(iterate.next() + " ");

}

}

}

输出:

The resultant values within the sub set:

6

9

10

18

20

程序2:

// Java code to illustrate subSet() method when TreeSet

// contains elements of String type

import java.io.*;

import java.util.Iterator;

import java.util.TreeSet;

public class Tree_Set_Demo {

public static void main(String[] args)

{

// Creating an empty TreeSet

TreeSet tree_set = new TreeSet();

// Adding the elements using add()

tree_set.add("Welcome");

tree_set.add("To");

tree_set.add("Geek");

tree_set.add("4");

tree_set.add("Geeks");

tree_set.add("TreeSet");

// Creating the subset tree

TreeSet sub_set = new TreeSet();

// Limiting the values till 5

sub_set = (TreeSet)tree_set.subSet("4", "TreeSet");

// Creating an Iterator

Iterator iterate;

iterate = sub_set.iterator();

// Displaying the tree set data

System.out.println("The resultant values within the sub set: ");

// Iterating through the subset

while (iterate.hasNext()) {

System.out.println(iterate.next() + " ");

}

}

}

输出:

The resultant values within the sub set:

4

Geek

Geeks

To

 类似资料: