Java TreeSet - floor() Method
The java.util.TreeSet.floor() method returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
Syntax
public E floor(E e)
Here, E is the type of element maintained by the container.
Parameters
e |
Specify the value to match. |
Return Value
Returns the greatest element less than or equal to e, or null if there is no such element.
Exception
- Throws ClassCastException, if the specified element cannot be compared with the elements currently in the set.
- Throws NullPointerException, if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.
Example:
In the example below, the java.util.TreeSet.floor() method returns the greatest element in the given set less than or equal to the specified value.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treeset TreeSet<Integer> MySet = new TreeSet<Integer>(); //populating the set MySet.add(10); MySet.add(20); MySet.add(30); MySet.add(40); //printing the set System.out.println("MySet contains: " + MySet); //printing the greatest element <= 25 System.out.println("Greatest Element <= 25: " + MySet.floor(25)); //printing the greatest element <= 5 System.out.println("Greatest Element <= 5: " + MySet.floor(5)); } }
The output of the above code will be:
MySet contains: [10, 20, 30, 40] Greatest Element <= 25: 20 Greatest Element <= 5: null
❮ Java.util - TreeSet