java winner tree_Java TreeMap.firstEntry()、firstKey()用法及代码示例

Java.util.TreeMap中有first()的两个变体,本文都将进行讨论。 1. firstEntry():它返回与此映射中最小键关联的键-值映射;如果映射为空,则返回null。

用法:

public Map.Entry firstEntry()

参数:

NA

返回值:

It returns an entry with the least key and null if the map is empty.

Exception:

NA

// Java code to demonstrate the working

// of firstKey()

import java.io.*;

import java.util.*;

public class firstKey {

public static void main(String[] args)

{

// Declaring the tree map of Integer and String

TreeMap treemap = new TreeMap();

// assigning the values in the tree map

// using put()

treemap.put(2, "two");

treemap.put(7, "seven");

treemap.put(3, "three");

treemap.put(1, "one");

treemap.put(6, "six");

treemap.put(9, "nine");

// use of firstEntry()

System.out.println("Lowest entry is:" + treemap.firstEntry());

}

}

输出:

Lowest entry is:1=one

2. firstKey():它返回Map中当前的第一个(最低)键。

用法:

public K firstKey()

参数:

NA

返回值:

It returns the first (lowest) key currently in this map.

Exception:

NA

NoSuchElementException: It is thrown if this map is empty.

// Java code to demonstrate the working

// of firstKey()

import java.io.*;

import java.util.*;

public class firstKey {

public static void main(String[] args)

{

// Declaring the tree map of Integer and String

TreeMap treemap = new TreeMap();

// assigning the values in the tree map

// using put()

treemap.put(2, "two");

treemap.put(1, "one");

treemap.put(3, "three");

treemap.put(6, "six");

treemap.put(5, "five");

treemap.put(9, "nine");

// Use of firstKey()

System.out.println("Lowest key is:" + treemap.firstKey());

}

}

输出:

Lowest key is:1

实际应用:这些功能可用于获取给定列表中排名最高的人,或者可用于在游戏中以最短的时间完成任务的人获胜的情况下分配赢家。下面讨论一个。

// Java code to demonstrate the application

// of firstKey() and firstEntry()

import java.io.*;

import java.util.*;

public class FirstAppli {

public static void main(String[] args)

{

// Declaring the tree map of Integer and String

// times of participants (in seconds)

TreeMap time = new TreeMap();

// assigning the time taken to complete task

// using put()

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");

// use of firstEntry()

// printing person with least time

System.out.println("Winner with lowest time is:" + time.firstEntry());

}

}

输出:

Winner with lowest time is:1.3=Shambhavi

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值