Java TreeSet floor(E e) Example

We have already seen first() method of java.util.TreeSet class which will return the first (lowest) element currently in this set whereas 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.

Signature

public E floor(E e) 

This method returns the greatest element in the set less than or equal to the given element in this set

Example

The following example shows the usage of java.util.TreeSet.floor() method.

import java.util.TreeSet;

public class FloorMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // Create treeSet1 object
        TreeSet treeSet1 = new TreeSet();
        
        //adding elements to TreeSet using add()
        treeSet1.add("Element1");
        treeSet1.add("Element5");
        treeSet1.add("Element4");
        treeSet1.add("Element2");
        
        //Lets check floor of Element3
        System.out.println("Floor of \"Element3\" : "+treeSet1.floor("Element3"));
    }
}

Output

Floor of "Element3" : Element2

Leave a Reply

Your email address will not be published. Required fields are marked *