Get Tail Set from TreeSet in Java

Java 8Object Oriented ProgrammingProgramming

To get the Tail Set from TreeSet, use the tailSet() method. Tail Set begins from a point and returns the elements greater than the element set in the beginning.

First, create a TreeSet and add elements −

TreeSet<String> set = new TreeSet<String>();
set.add("78");
set.add("56");
set.add("88");
set.add("54");
set.add("76");
set.add("34");

Now, get the Tail Set −

SortedSet sorted = set.tailSet("56");

The following is an example to get Tail Set from TreeSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> set = new TreeSet<String>();
      set.add("78");
      set.add("56");
      set.add("88");
      set.add("54");
      set.add("76");
      set.add("34");
      System.out.println("TreeSet elements...");
      Iterator<String> i = set.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
      SortedSet sorted = set.tailSet("56");
      System.out.println("TailSet = " + sorted);
   }
}

Output

TreeSet elements...
34
54
56
76
78
88
TailSet = [56, 76, 78, 88]
raja
Published on 11-Jan-2019 11:09:23
Advertisements