Java Program to get Tail Set from TreeSet

Java 8Object Oriented ProgrammingProgramming

Let us first create a TreeSet and add elements to it:

TreeSet<Integer> treeSet = new TreeSet<Integer>();
treeSet.add(20);
treeSet.add(50);
treeSet.add(100);
treeSet.add(120);
treeSet.add(150);
treeSet.add(200);
treeSet.add(250);
treeSet.add(300);
treeSet.add(350);
treeSet.add(400);

Now, let us get Tail Set from the TreeSet. In the below case, we will get elements above 200:

SortedSet<Integer> set = treeSet.tailSet(200);

Example

import java.util.SortedSet;
import java.util.TreeSet;
public class Demo {
   public static void main(String[] args) {
      TreeSet<Integer> treeSet = new TreeSet<Integer>();
      treeSet.add(20);
      treeSet.add(50);
      treeSet.add(100);
      treeSet.add(120);
      treeSet.add(150);
      treeSet.add(200);
      treeSet.add(250);
      treeSet.add(300);
      treeSet.add(350);
      treeSet.add(400);
      SortedSet<Integer> set = treeSet.tailSet(200);
      System.out.println("Tail Set = " + set);
      set = treeSet.tailSet(300);
      System.out.println("Tail Set = " + set);
      set = treeSet.tailSet(100);
      System.out.println("Tail Set = " + set);
   }
}

Output

Tail Set = [200, 250, 300, 350, 400]
Tail Set = [300, 350, 400]
Tail Set = [100, 120, 150, 200, 250, 300, 350, 400]
raja
Published on 25-Apr-2019 15:43:38
Advertisements