What is the NavigableSet.lower() method in Java?
In this shot, we will learn how to use the NavigableSet.lower() method in Java.
Introduction
The NavigableSet.lower() method is present in the NavigableSet interface inside the java.util package.
NavigableSet.lower() is used to obtain the greatest element strictly less than the given element in the set.
It results null if there is no such element in the set.
Let’s understand with the help of an example. Suppose that a NavigableSet contains [1, 5, 3, 9, 10, 11, 16, 19]. The element for which we need to determine the lower element will be 11. So, the result of NavigableSet.lower() is 10.
When we add the elements in the
NavigableSet, they get stored in the sorted form. If theNavigableSetis of the String type, the elements get stored in alphabetical order, irrespective of string length.
Syntax
E lower(E e)
Parameters
The NavigableSet.low() accepts one parameter, i.e., the element type that is the same as elements maintained by this set container.
Return value
The NavigableSet.lower() method returns the greatest element that is lower than the specified element from the set.
Code
Let’s have a look at the code below:
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("Greatest element less than 10 is: " + s.lower(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
TreeSetof Integer type. TheNavigableSetis inherited fromSortedSetwhich is actually only inherited fromTreeSet. AsSortedSetandNavigableSetare interfaces, we cannot instantiate an object from them. -
From lines 10 to 16, we added the elements into the
NavigableSetby using theadd()method. -
From line 18, we used the
NavigableSet.lower()method and displayed the result with a message.
So, this is how to use the NavigableSet.lower() method in Java.