當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java NavigableMap ceilingKey()用法及代碼示例


Java中NavigableMap接口的ceilingKey()方法用於返回大於或等於給定鍵的最小鍵;如果不存在這樣的鍵,則返回null。

用法

K ceilingKey(K key)

其中,K是此映射容器維護的Key的類型。


參數:它接受單個參數Key,該參數是要映射的 key ,並且屬於此collection接受的 key 類型。

返回值:返回大於或等於給定鍵的最小鍵;如果不存在這樣的鍵,則返回null。

以下程序說明了Java中的ceilingKey()方法:

程序1:當鍵為整數時。

// Java code to demonstrate the working of 
// ceilingKey()  method 
  
import java.io.*; 
import java.util.*; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // Declaring the NavigableMap of Integer and String 
        NavigableMap<Integer, String> tmmp = new TreeMap<>(); 
  
        // assigning the values in the NavigableMap 
        // using put() 
        tmmp.put(2, "two"); 
        tmmp.put(7, "seven"); 
        tmmp.put(3, "three"); 
  
        // Use of ceilingKey() 
        // returns 7( next greater key) 
        System.out.println("The next greater key of 6 is : "
                           + tmmp.ceilingKey(6)); 
  
        // returns "null" as no value present 
        // greater than or equal to number 
        System.out.println("The next greater key of 3 is : " 
                                       + tmmp.ceilingKey(3)); 
    } 
}
輸出:
The next greater key of 6 is : 7
The next greater key of 3 is : 3

程序2:當鍵是字符串時。

// Java code to demonstrate the working of 
// ceilingKey()  method 
  
import java.io.*; 
import java.util.*; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // Declaring the NavigableMap of Integer and String 
        NavigableMap<String, String> tmmp = new TreeMap<>(); 
  
        // assigning the values in the NavigableMap 
        // using put() 
        tmmp.put("one", "two"); 
        tmmp.put("six", "seven"); 
        tmmp.put("two", "three"); 
  
        // Use of ceilingKey() 
        // returns 7( next greater key) 
        System.out.println("The next greater key of five is : "
                           + tmmp.ceilingKey("five")); 
  
        // returns "null" as no value present 
        // greater than or equal to number 
        System.out.println("The next greater key of six is : " +  
                                         tmmp.ceilingKey("six")); 
    } 
}
輸出:
The next greater key of five is : one
The next greater key of six is : six

參考: https://docs.oracle.com/javase/10/docs/api/java/util/NavigableMap.html#ceilingKey(K)



相關用法


注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 NavigableMap ceilingKey() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。