Java Program to get headset from TreeSet

Java 8Object Oriented ProgrammingProgramming

To get HeadSet from TreeSet, at first create a TreeSet and add some elements:

TreeSet<String> treeSet = new TreeSet<String>();
treeSet.add("ABC");
treeSet.add("DEF");
treeSet.add("GHI");
treeSet.add("JKL");
treeSet.add("MNO");
treeSet.add("PQR");

To get headset, use the headset() method:

SortedSet<String> set = treeSet.headSet("MNO");
System.out.println("Head Set = " + set);

You can also change the value like this:

set = treeSet.headSet("GHI");
System.out.println("Head Set = " + set);

Example

import java.util.SortedSet;
import java.util.TreeSet;
public class Demo {
   public static void main(String[] args) {
      TreeSet<String> treeSet = new TreeSet<String>();
      treeSet.add("ABC");
      treeSet.add("DEF");
      treeSet.add("GHI");
      treeSet.add("JKL");
      treeSet.add("MNO");
      treeSet.add("PQR");
      SortedSet<String> set = treeSet.headSet("MNO");
      System.out.println("Head Set = " + set);
      set = treeSet.headSet("GHI");
      System.out.println("Head Set = " + set);
      set = treeSet.headSet("ABC");
      System.out.println("Head Set = " + set);
   }
}

Output

Head Set = [ABC, DEF, GHI, JKL]
Head Set = [ABC, DEF]
Head Set = []
raja
Published on 24-Apr-2019 13:01:46
Advertisements