Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the NavigableSet.ceiling() method in Java?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The NavigableSet.ceiling() method is used to obtain the lowest element that is equal to or greater than the given element in the set.

The NavigableSet.ceiling() method is present in the NavigableSet interface inside the java.util package.

It results null if there is no such element in the set.

Example

Let’s understand with the help of an example. Suppose that a NavigableSet contains [1, 5, 3, 9, 10, 11, 16, 19].

Let the element for which we need to determine the ceiling be 1111.

So, the result of NavigableSet.ceiling() is 16.

Parameter

NavigableSet.ceiling()accepts one parameter, i.e., the element for which we need to determine the ceiling value.

Return value

It returns the lowest element that is equal to or greater than the given element in the set.

Code

Let’s have a look at the code.

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("Least element greater than or equal to 11 is: " + s.ceiling(11));
}
}
Use NavigableSet.ceiling() function in Java

Explanation

  • In lines 1 and 2, we imported the required packages and classes.

  • In line 4, we made a Main class.

  • In line 5, we made a main() function.

  • In line 6, we created a TreeSet of Integer type. The NavigableSet is inherited from SortedSet, inherited from TreeSet only.

    As SortedSet and NavigableSet are interfaces, we cannot instantiate an object of them.

  • From lines 7 to 13, we added the elements into the NavigableSet by using the add() method.

  • In line 15, we used the NavigableSet.ceiling() method and displayed the result with a message.

In this way, we can use the NavigableSet.ceiling() method in Java.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring