What is the NavigableSet.tailSet() method in Java?
The NavigableSet.tailSet() method is present in the NavigableSet interface inside the java.util package.
NavigableSet.tailSet() is available in two variations:
- First variation: This variation is used to obtain the parts of the set whose elements are greater than or equal to the element.
SortedSet<E> tailSet(E fromElement)
- Second variation: This variation of the
NavigableSet.tailSet()function is used to obtain the parts of the set whose elements are greater than the element specified if thepred(boolean value) isfalse.
NavigableSet<E> tailSet(E Element, boolean inclusive)
When we add the elements in the
NavigableSet, they get stored in the sorted form. If theNavigableSetis of String type, the elements get stored in alphabetical order, irrespective of string length.
Parameters
The first variation of the NavigableSet.tailSet() accepts only one parameter:
- The element which is the lowest point for the returned range.
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 asfalsewhen the lowest starting point is to not be included in the returned view.
Return value
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.
Code
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));}}
Explanation
-
In lines 1 and 2, we imported the required packages and classes.
-
In line 4 we made a
Mainclass. -
In line 6, we made a
main()function. -
In line 8, we created a
TreeSetof Integer type. TheNavigableSetis inherited fromSortedSet, which is actually inherited fromTreeSetonly. AsSortedSetandNavigableSetare interfaces, we cannot instantiate an object of them. -
From lines 10 to 16, we added the elements into the
NavigableSetby using theadd()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 obtaintailSetand displayed the result with a message.
So, this is how to use the NavigableSet.tailSet() method in Java.