查找大于SortedMap中的第一个值(Finding the first value greater than in a SortedMap)

编程入门 行业动态 更新时间:2024-10-26 06:27:12
查找大于SortedMap中的第一个值(Finding the first value greater than in a SortedMap)

我想知道有什么更好的方法来找到大于SortedMap中的输入值的第一个值,而不是循环遍历下例中的所有值。 或者,如果SortedMap是用于此的最佳结构。

这可以通过谷歌收藏来实现吗? 提前致谢

public class mapTest { public static void main(String[] args) { SortedMap<Double, Object> sortedMap = new TreeMap<Double, Object>(); sortedMap.put(30d, "lala"); sortedMap.put(10d, "foo"); sortedMap.put(25d, "bar"); System.out.println("result: " + findFirstValueGreaterThan(sortedMap, 28d)); } public static Object findFirstValueGreaterThan(SortedMap<Double, Object> sortedMap, Double value) { for (Entry<Double, Object> entry : sortedMap.entrySet()) { if (entry.getKey() > value) { // return first value with a key greater than the inputted value return entry.getValue(); } } return null; } }

I'd like to know what is there a better way to find the first value greater than an inputted value in a large SortedMap instead of looping through all values in my example below. Or if SortedMap is a the best structure to use for this.

Could this be achieved using google-collections? Thanks in advance

public class mapTest { public static void main(String[] args) { SortedMap<Double, Object> sortedMap = new TreeMap<Double, Object>(); sortedMap.put(30d, "lala"); sortedMap.put(10d, "foo"); sortedMap.put(25d, "bar"); System.out.println("result: " + findFirstValueGreaterThan(sortedMap, 28d)); } public static Object findFirstValueGreaterThan(SortedMap<Double, Object> sortedMap, Double value) { for (Entry<Double, Object> entry : sortedMap.entrySet()) { if (entry.getKey() > value) { // return first value with a key greater than the inputted value return entry.getValue(); } } return null; } }

最满意答案

这些都在文档中:

ceilingKey(K键) 返回大于或等于给定键的最小键,如果不存在这样的键,则返回null。

所以,

findFirstValueGreaterThan(sortedMap, 28d)

应该

sortedMap.ceilingKey(28d)

不过,关注“大于”和“大于或等于”之间的区别。

It's all in the docs:

ceilingKey(K key) Returns the least key greater than or equal to the given key, or null if there is no such key.

So,

findFirstValueGreaterThan(sortedMap, 28d)

should be

sortedMap.ceilingKey(28d)

Pay attention at difference between "greater than" and "greater than or equal to", though.

更多推荐

本文发布于:2023-08-04 08:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1413046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   SortedMap   greater   Finding

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!