Get Sub Set from TreeSet in Java

Java 8Object Oriented ProgrammingProgramming

To get the sub set from TreeSet, use the subSet() method. Let us first create a TreeSet and add elements to it −

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

Let us get the subset now from a range of elements −

SortedSet sorted = set.subSet("54", "76");

The following is an example to get sub set from Java 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.subSet("54", "76");
      System.out.println("SubSet = " + sorted);
   }
}

Output

TreeSet elements...
34
54
56
76
78
88
SubSet = [54, 56]
raja
Published on 11-Jan-2019 06:33:25
Advertisements