Java NavigableMap lowerKey()方法

Java NavigableMap lowerKey()方法

NavigableMap接口的lowerKey()方法是用来返回严格小于给定键的最大键,作为参数传递。更简单地说,这个方法是用来寻找作为参数传递的元素之后的下一个最大的元素。

语法

public K NavigableMap.lowerKey(K key)

参数。这个方法需要一个强制性的参数key,也就是要匹配的key。

返回值: 该方法返回严格小于key的最大key,如果没有这样的key,则返回null。

异常: 该方法会抛出以下异常。

  • ClassCastException :当指定的键不能与Map中可用的键进行比较时。
  • NullPointerException : 当map中指定的键是空的,并且它使用自然
    排序,这意味着比较器不允许空键。

下面的程序说明了 lowerKey() 方法的使用。

例1 :

// Java program to demonstrate lowerKey() method
  
import java.util.*;
  
public class FloorKeyDemo {
    public static void main(String args[])
    {
  
        // create an empty TreeMap
        NavigableMap<Integer, String>
            navMap = new TreeMap<Integer, String>();
  
        // Insert the values
        navMap.put(6, "Six");
        navMap.put(1, "One");
        navMap.put(5, "Five");
        navMap.put(3, "Three");
        navMap.put(8, "Eight");
        navMap.put(10, "Ten");
  
        // Print the Values of TreeMap
        System.out.println("TreeMap: " + navMap.toString());
  
        // Get the greatest key mapping of the Map
  
        // As here 9 is not available it returns 8
        // because 9 is strictly less than 11, present
        System.out.print("Lower Key Entry of Element 9 is: ");
        System.out.println(navMap.lowerKey(9));
  
        // Though, 3 is available in the Map
        // it returns 1 because this method returns
        // strictly less than key according to the specified key
        System.out.print("Lower Key Entry of Element 3 is: ");
        System.out.println(navMap.lowerKey(3));
    }
}

输出:

TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Lower Key Entry of Element 9 is: 8
Lower Key Entry of Element 3 is: 1

例2: 演示NullPointerException

// Java program to demonstrate lowerKey() method
  
import java.util.*;
  
public class FloorKeyDemo {
    public static void main(String args[])
    {
  
        // create an empty TreeMap
        NavigableMap<Integer, String>
            navMap = new TreeMap<Integer, String>();
  
        // Insert the values
        navMap.put(6, "Six");
        navMap.put(1, "One");
        navMap.put(5, "Five");
        navMap.put(3, "Three");
        navMap.put(8, "Eight");
        navMap.put(10, "Ten");
  
        // Print the Values of TreeMap
        System.out.println("TreeMap: " + navMap.toString());
  
        try {
            // Passing null as parameter to lowerKey()
            // This will throw exception
            System.out.println(navMap.lowerKey(null));
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

输出:

TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Exception: java.lang.NullPointerException

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程