Java 使用上限方法获得大于指定元素的TreeSet元素

Java 使用上限方法获得大于指定元素的TreeSet元素

使用Java中的 ceiling() 方法获得大于指定元素的TreeSet元素。Java中的天花板方法返回集合中大于或等于给定元素的最小元素,如果没有这样的元素,则返回空。

java.util.TreeSet 类的 ceiling() 方法用于返回这个集合中大于或等于给定元素的最小元素,如果没有这样的元素,则返回空。

语法:

public E ceiling(E e)

参数: 作为一个要匹配的参数。

返回值: 如果没有这样的元素。

例外情况: 如果指定的元素是空的,并且这个集合使用自然排序,或者它的比较器不允许空元素。

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

示例 1:

// 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));
    }
}

输出

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

示例 2:

// 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));
    }
}

输出

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程