What is the NavigableSet.higher() method in Java?
The NavigableSet.higher() method is used to obtain the lowest element strictly greater than a given element in a set.
It returns null if there is no such element in the set.
The
NavigableSet.higher()method is present in theNavigableSetinterface inside thejava.utilpackage.
Let’s understand with the help of an example.
Suppose that a NavigableSet contains [1, 5, 3, 9, 10, 11, 16, 19]. Let be the element for which we need to determine the higher element. So, the result of NavigableSet.higher() is .
When we add the elements in the
NavigableSet, they get stored in a sorted form. If theNavigableSetis ofStringtype, the elements get stored in alphabetical order irrespective of string length.
Parameters
The NavigableSet.higher() method accepts one parameter, i.e., the element of the type of the elements maintained by this Set container.
Return value
The NavigableSet.higher() method returns the lowest element greater than the specified element from the set.
Code
Let us 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("Lowest element greater than 10 is: " + s.higher(10));}}
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
TreeSetofIntegertype. TheNavigableSetis inherited fromSortedSetwhich 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
NavigableSet.higher()method and displayed the result with a message.
In this way, we can use the NavigableSet.higher() method in Java.