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


Java TreeMap ceilingEntry()、ceilingKey()用法及代碼示例


Java.util.TreeMap中有ceilingEntry()的兩個變體,本文都將進行討論。

1. ceilingEntry(K Key):用於返回與大於或等於給定鍵的最小鍵關聯的鍵值映射,如果沒有這樣的鍵,則返回null。

用法:
public Map.Entry ceilingEntry(K key)
參數:
key: The key to be matched.
返回值:
It returns the entry with the least key greater than or equal to key, and null if 
there is no such key.
Exception:
ClassCastException: It throws the exception if the specified key cannot be compared
with the keys currently in the map.
NullPointerException: It throws the exception if the specified key is null. 

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

輸出:


The next greater key-value of 5 is:7=seven
The next greater key-value of 8 is:null

2. ceilingKey(K key):它與上一個 key 具有相同的工作,但唯一的不同是它不包含mapped-keys。它僅返回大於或等於給定 key 的最小 key ,否則返回NULL。 。

用法:
public K ceilingKey(K key)
參數:
key: The key to be matched.
返回值:
It returns the entry with the least key greater than or equal to key, and null 
if there is no such key.
Exception:
ClassCastException: It throws the exception if the specified key cannot be compared
with the keys currently in the map.
NullPointerException: It throws the exception if the specified key is null. 

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

輸出:

The next greater key of 5 is:7
The next greater key of 8 is:null



相關用法


注:本文由純淨天空篩選整理自 TreeMap ceilingEntry() and ceilingKey() methods in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。