Last Updated : 11 Jul, 2025
The headSet() method of
NavigableSet interface in Javais used to return a view of the portion of this set whose elements range from
fromElementto
toElement.
: The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range.
Syntax:
NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive);
Where, E is the type of elements maintained by this Set container.
Parameters: This function accepts 4 parameters as explained below:
: It returns a view of the portion of this set whose elements range from fromElement to toElement. Below programs illustrate the subSet() method in Java:
Program 1: NavigableSet with integer elements.
Java
// A Java program to demonstrate
// subSet() method of NavigableSet
import java.util.NavigableSet;
import java.util.TreeSet;
public class GFG {
public static void main(String[] args)
{
NavigableSet<Integer> ns = new TreeSet<>();
ns.add(0);
ns.add(1);
ns.add(2);
ns.add(3);
ns.add(4);
ns.add(5);
ns.add(6);
System.out.println("Map with key-value between the given argument : "
+ ns.subSet(1, 6));
System.out.println("Map with key-value between the given argument : "
+ ns.subSet(2, 6));
}
}
Output:
Map with key-value between the given argument : [1, 2, 3, 4, 5] Map with key-value between the given argument : [2, 3, 4, 5]Program 2:
NavigableSet with string elements.
Java
// A Java program to demonstrate
// subSet() method of NavigableSet
import java.util.NavigableSet;
import java.util.TreeSet;
public class GFG {
public static void main(String[] args)
{
NavigableSet<String> ns = new TreeSet<>();
ns.add("A");
ns.add("B");
ns.add("C");
ns.add("D");
ns.add("E");
ns.add("F");
ns.add("G");
System.out.println("Map with key-value between the given range : "
+ ns.subSet("B", "G"));
}
}
Output:
Map with key-value between the given range : [B, C, D, E, F]Reference
:
https://docs.oracle.com/javase/10/docs/api/java/util/NavigableSet.html#subSet(E, E)RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4