Java中的TreeMap firstEntry()和firstKey()方法及其示例

Java中first()的变体。util。TreeMap,本文将讨论这两种方法。

null

方法1: firstEntry()

它返回一个与该映射中最小键关联的键值映射,如果映射为空,则返回null。

语法:

public Map.Entry firstEntry()

返回类型: 具有最少键的条目,如果映射为空,则为null。

例子:

JAVA

// Java Program to Illustrate Working of firstKey() Method
// of TreeMap class
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty TreeMap by
// declaring object of integer, strings pairs
TreeMap<Integer, String> treemap
= new TreeMap<Integer, String>();
// Populating values in the TreeMap
// using put() method
treemap.put( 2 , "two" );
treemap.put( 7 , "seven" );
treemap.put( 3 , "three" );
treemap.put( 1 , "one" );
treemap.put( 6 , "six" );
treemap.put( 9 , "nine" );
// Printing the lowest entry in TreeMap by
// using firstEntry() method
System.out.println( "Lowest entry is: "
+ treemap.firstEntry());
}
}


输出:

Lowest entry is: 1=one

方法2:firstKey()

它返回 第一(最低) 当前在地图中输入。

语法:

public K firstKey()

返回类型: 此地图中当前的第一个(最低)键。

引发异常: 非接触性异常 如果此地图为空,则会引发。

例子:

JAVA

// Java Program to Demonstrate firstKey() Method
// of TreeMap class
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty TreeMap by
// declaring object of integer, strings pairs
TreeMap<Integer, String> treemap
= new TreeMap<Integer, String>();
// Populating values in the TreeMap
// using put() method
treemap.put( 2 , "two" );
treemap.put( 1 , "one" );
treemap.put( 3 , "three" );
treemap.put( 6 , "six" );
treemap.put( 5 , "five" );
treemap.put( 9 , "nine" );
// Printing the lowest entry in TreeMap by
// using firstKey() method
System.out.println( "Lowest key is: "
+ treemap.firstKey());
}
}


输出:

Lowest key is: 1

实施: 这些函数可用于获取给定列表中排名最佳的人,或用于指定完成任务时间最短的人获胜的获胜者。下文将讨论后一种情况。

例子: 实际应用

JAVA

// Java Program to Demonstrate Application Usage
// of firstKey() and firstEntry() Methods
// of TreeMap class
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty TreeMap
// of Integer and String times of participants
// In seconds
TreeMap<Float, String> time
= new TreeMap<Float, String>();
// Populating the time taken to complete task
// using put() method
time.put( 2 .32f, "Astha" );
time.put( 7 .43f, "Manjeet" );
time.put( 1 .3f, "Shambhavi" );
time.put( 5 .63f, "Nikhil" );
time.put( 6 .26f, "Vaishnavi" );
// Printing person with least time
// using of firstEntry() method
System.out.println( "Winner with lowest time is : "
+ time.firstEntry());
}
}


输出:

Winner with lowest time is : 1.3=Shambhavi

本文由 沙姆巴维·辛格 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享