java ceilingentry_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 treemap = new TreeMap();

// 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 treemap = new TreeMap();

// 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值