Java Program to get Sub Set from TreeSet

Java 8Object Oriented ProgrammingProgramming

Let us first create a TreeSet and add elements:

TreeSet<Integer> treeSet = new TreeSet<Integer>();
treeSet.add(10);
treeSet.add(20);
treeSet.add(30);
treeSet.add(40);
treeSet.add(50);
treeSet.add(60);
treeSet.add(70);
treeSet.add(80);
treeSet.add(90);
treeSet.add(100);

Now, let’s say you need to set sub set from 50 to 70, then use the subset() for it:

SortedSet<Integer> sub = treeSet.subSet(50, 70);
System.out.println("Sub Set = " + sub);

Example

import java.util.TreeSet;
import java.util.SortedSet;
public class Demo {
   public static void main(String[] args) {
      TreeSet<Integer> treeSet = new TreeSet<Integer>();
      treeSet.add(10);
      treeSet.add(20);
      treeSet.add(30);
      treeSet.add(40);
      treeSet.add(50);
      treeSet.add(60);
      treeSet.add(70);
      treeSet.add(80);
      treeSet.add(90);
      treeSet.add(100);
      SortedSet<Integer> sub = treeSet.subSet(50, 70);
      System.out.println("Sub Set = " + sub);
      sub = treeSet.subSet(80, 90);
      System.out.println("Sub Set = " + sub);
      sub = treeSet.subSet(10, 90);
      System.out.println("Sub Set = " + sub);
   }
}

Output

Sub Set = [50, 60]
Sub Set = [80]
Sub Set = [10, 20, 30, 40, 50, 60, 70, 80]
raja
Published on 25-Apr-2019 15:41:30
Advertisements