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


Java TreeMap firstEntry()用法及代碼示例


TreeMap firstEntry()是指用於檢索與TreeMap中存在的最低鍵值元素映射的鍵值對的方法,如果Map中沒有鍵值對,則僅返回null。方法名稱“ firstEntry()”本身說明,它將返回鍵元素最少的條目及其值。

Syntax:public Map.Entry<K,V> firstEntry(), 

Here K and V refer key-value respectively.

Parameters:NA - As it doesnot accept any parameter.

Return Value: It returns an entry with the least key (lowest key-value pair) and null if the 
TreeMap is empty.

Exception:NA - As it doesnot throw any exception at entry return.

範例1:

Java

// Java code to demonstrate  
// the working of TreeMap firstKey()  
import java.io.*;  
import java.util.*;  
public class treeMapFirstKey {  
public static void main(String[] args)  
    {  
    
        // Declaring the TreeMap of Key - Value Pairs 
        // Integer - Key , String - Value 
        TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();  
    
        // Adding-up the values in the TreeMap  
        // Use put() function to append data  
        treemap.put(2, "Java");  
        treemap.put(4, "CPP");  
        treemap.put(5, "PHP");  
        treemap.put(1, "Python");  
        treemap.put(3, "C");  
    
        // Check for firstEntry() 
        System.out.println("Lowest Entry is:" + treemap.firstEntry());  
    }  
}
輸出
Lowest Entry is:1=Python

在上麵的示例中,很明顯firstEntry()檢查會比較TreeMap的每個鍵,並返回鍵值對最小的鍵。

範例2:

Java

// Java code to demonstrate the working 
// of TreeMap firstKey() method 
import java.io.*;  
import java.util.*;  
public class percentageFirstKey {  
public static void main(String[] args)  
    {  
    
        // Declaring the TreeMap of Key - Value Pairs 
        // Double - Key , String - Value 
        TreeMap<Double, String> treemapPercentage = new TreeMap<Double, String>();  
    
        // Adding-up the values in the TreeMap  
        // Use put() function to append data  
        treemapPercentage.put(81.40, "Shashank");  
        treemapPercentage.put(72.80, "Anand"); 
        treemapPercentage.put(65.50, "Gulshan"); 
        treemapPercentage.put(71.10, "Abhishek");  
        treemapPercentage.put(70.20, "Ram");  
    
        // Check for firstEntry() 
        System.out.println("Lowest Entry is:" + treemapPercentage.firstEntry());  
    }  
}
輸出
Lowest Entry is:65.5=Gulshan

TreeMap firstEntry()上的一些要點:

  • TreeMap firstEntry()在java.util軟件包中可用。
  • 在返回條目時它不會引發異常。
  • TreeMap firstEntry()方法是非靜態方法,因為類的對象可以訪問該方法,否則將產生錯誤。




相關用法


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