Saturday 14 July 2012

Get Sub Set from Java TreeSet example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
  Get Sub Set from Java TreeSet example
  This Java Example shows how to get the sub Set from Java TreeSet by giving specific
  range of values using subSet method of Java TreeSet class.
 */

import java.util.TreeSet;
import java.util.SortedSet;

public class GetSubSetFromTreeSetExample {

 public static void main(String[] args) {

  // create TreeSet object
  TreeSet tSet = new TreeSet();

  // add elements to TreeSet
  tSet.add("1");
  tSet.add("3");
  tSet.add("2");
  tSet.add("5");
  tSet.add("4");

  /*
   * To get the sub Set from Java TreeSet use, SortedSet subSet(int from,
   * int to) method of TreeSet class.
   * 
   * This method returns portion of the TreeSet whose elements range from
   * from (inclusive) to to(exclusive).
   * 
   * Please note that, the SortedSet returned by this method is backed by
   * the original TreeSet. So any changes made to SortedSet will be
   * reflected back to original TreeSet.
   */

  SortedSet sortedSet = tSet.subSet("2", "5");

  System.out.println("SortedSet Contains : " + sortedSet);

 }
}

/*
 * Output would be SortedSet Contains : [2, 3, 4]
 */

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...