Open In App

Getting TreeSet Element Greater than Specified Element using Ceiling Method in Java

Last Updated : 16 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

To get TreeSet Element Greater than Specified Element using ceiling() Method in Java. The ceiling method in Java return the least element in the set greater than or equal to the given element, or null if there is no such element.

The ceiling() method of java.util.TreeSet<E> class is used to return the least element in this set greater than or equal to the given element, or null if there is no such element.

Syntax:

public E ceiling(E e)

Parameters: This method takes the value e as a parameter which is to be matched.

Return Value: This method returns the least element greater than or equal to e, or null if there is no such element.

Exception: This method throws NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.

set = {10,20,30,40,50}

// Least element in the set greater than or equal to the 23
Ceiling value of 23: 30

// There is no such element so it returns null
Ceiling value of 55: null

Example 1:

Java




// Java Program demonstrate how to get TreeSet Element
// Greater than Specified Element using ceiling() 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 ceiling of 23
        System.out.println("Ceiling value of 23: "
                           + set.ceiling(23));
    }
}


 
 

Output

TreeSet: [10, 20, 30, 40, 50]
Ceiling value of 23: 30

 

Example 2:

 

Java




// Java Program demonstrate how to get TreeSet Element
// Greater than Specified Element using ceiling() 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 ceiling of 55
        System.out.println("Ceiling value of 55: "
                           + set.ceiling(55));
    }
}


 
 

Output

TreeSet: [10, 20, 30, 40, 50]
Ceiling value of 55: null

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads