Java 使用Floor方法获得比指定元素小的TreeSet元素

Java 使用Floor方法获得比指定元素小的TreeSet元素

使用Java中的floor()方法获得小于指定元素的TreeSet元素。TreeSet用于以排序的方式存储元素。floor方法返回集合中小于或等于给定元素的最大元素,如果没有这样的元素则为空。

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

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

语法:

public E floor(E e)

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

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

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

示例 1:

// 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

示例 2:

// 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程