The NavigableSet.tailSet()
method is present in the NavigableSet
interface inside the java.util
package.
NavigableSet.tailSet()
is available in two variations:
SortedSet<E> tailSet(E fromElement)
NavigableSet.tailSet()
function is used to obtain the parts of the set whose elements are greater than the element specified if the pred
(boolean value) is false
.NavigableSet<E> tailSet(E Element, boolean inclusive)
When we add the elements in the
NavigableSet
, they get stored in the sorted form. If theNavigableSet
is of String type, the elements get stored in alphabetical order, irrespective of string length.
The first variation of the NavigableSet.tailSet()
accepts only one parameter:
The second variation of NavigableSet.tailSet()
accepts two parameters:
Element
: The element which is the lowest point for the returned range.inclusive
: It is specified as false
when the lowest starting point is to not be included in the returned view.The first variation of the NavigableSet.tailSet()
method returns the set in which the elements are greater than or equal to the element.
The second NavigableSet.tailSet()
method returns the set in which the elements are greater than the element passed in the argument if the pred
is passed as false
.
Let’s have a look at the code.
import java.util.NavigableSet;import java.util.TreeSet;class Main{public static void main(String[] args){NavigableSet<Integer> s = new TreeSet<Integer>();s.add(6);s.add(8);s.add(5);s.add(3);s.add(9);s.add(10);s.add(17);System.out.println("Values greater than or equal to 6 are: " + s.tailSet(6));System.out.println("Values greater than 6 are: " + s.tailSet(6, false));}}
In lines 1 and 2, we imported the required packages and classes.
In line 4 we made a Main
class.
In line 6, we made a main()
function.
In line 8, we created a TreeSet
of Integer type. The NavigableSet
is inherited from SortedSet
, which is actually inherited from TreeSet
only. As SortedSet
and NavigableSet
are interfaces, we cannot instantiate an object of them.
From lines 10 to 16, we added the elements into the NavigableSet
by using the add()
method.
From line 18, we used the first variation of NavigableSet.tailSet()
method to obtain tailSet and displayed the result with a message.
In line 19, we used the second variation of the NavigableSet.tailSet()
method to obtain tailSet
and displayed the result with a message.
So, this is how to use the NavigableSet.tailSet()
method in Java.