To get TreeSet Element smaller than Specified Element using floor() Method in Java.The TreeSet is used to store elements in sorted order. The floor method returns the greatest element in the set less than or equal to the given element, or null if there is no such element.
set = {10,20,30,40,50} // greatest element in the set less than or equal to the 23 Floor value of 23: 20 // There is no such element so it returns null Floor value of 5: null
The floor() method of java.util.TreeSet<E> class is used to return 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)
Parameters: This method takes the value e as a parameter which is to be matched.
Return Value: This method returns the greatest element less than or equal to e, or null if there is no such element
Exception: This method throws the NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.
Example 1:
Java
// Java Program demonstrate how to get TreeSet Element // Smaller than Specified Element using Floor Method import java.util.*; public class GFG { public static void main(String[] args) { // New TreeSet TreeSet<Integer> set = new TreeSet<>(); // Adding element to TreeSet set.add( 40 ); set.add( 50 ); set.add( 30 ); set.add( 10 ); set.add( 20 ); // Print TreeSet System.out.println( "TreeSet: " + set); // Print floor value of 23 System.out.println( "Floor value of 23: " + set.floor( 23 )); } } |
TreeSet: [10, 20, 30, 40, 50] Floor value of 23: 20
Example 2:
Java
// Java Program demonstrate how to get TreeSet Element // Smaller than Specified Element using Floor Method import java.util.*; class GFG { public static void main(String[] args) { // New TreeSet TreeSet<Integer> set = new TreeSet<>(); // Adding element to TreeSet set.add( 40 ); set.add( 50 ); set.add( 30 ); set.add( 10 ); set.add( 20 ); // Print TreeSet System.out.println( "TreeSet: " + set); // Print floor value of 5 System.out.println( "Floor value of 5: " + set.floor( 5 )); } } |
TreeSet: [10, 20, 30, 40, 50] Floor value of 5: null