How to use headSet() method of Java NavigableSet Class

Java 8Object Oriented ProgrammingProgramming

The headset() method returns elements up to a limit defined as a parameter.

First, create a NavigableSet and add elements −

NavigableSet<Integer> set = new TreeSet<>();
set.add(10);
set.add(25);
set.add(40);
set.add(55);
set.add(70);
set.add(85);
set.add(100);

Now, use the headset() method −

set.headSet(55));

The following is an example −

Example

 Live Demo

import java.util.NavigableSet;
import java.util.TreeSet;
public class Demo {
   public static void main(String[] args) {
      NavigableSet<Integer> set = new TreeSet<>();
      set.add(10);
      set.add(25);
      set.add(40);
      set.add(55);
      set.add(70);
      set.add(85);
      set.add(100);
      System.out.println("Returned Value = " + set.headSet(55));
      System.out.println("Returned Value (high endpoint included) = " + set.headSet(55, true));
   }
}

Output

Returned Value = [10, 25, 40]
Returned Value (high endpoint included) = [10, 25, 40, 55]
raja
Published on 30-Jan-2019 10:44:52
Advertisements