Get Head Set from Java TreeSet

Java 8Object Oriented ProgrammingProgramming

To get Head Set, you need to use the headset() method. This allow a user to get a set of elements in sorted order.

Firstly, set the TreeSet and add elements

TreeSet<String> tSet = new TreeSet<String>();
tSet.add("P");
tSet.add("Q");
tSet.add("R");
tSet.add("S");

Let us now get the Head Set

SortedSet s = tSet.headSet("S");

The following is an example to get Head Set from TreeSet in Java

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> tSet = new TreeSet<String>();
      tSet.add("P");
      tSet.add("Q");
      tSet.add("R");
      tSet.add("S");
      System.out.println("TreeSet elements...");
      Iterator i = tSet.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
      SortedSet s = tSet.headSet("S");
      System.out.println("Head Set has = " + s);
   }
}

Output

The output is as follows

TreeSet elements...
P
Q
R
S
Head Set has = [P, Q, R]
raja
Published on 17-Jan-2019 09:48:15
Advertisements