如何获取地图中的上一个键/值和下一个键/值 [英] How to get the previous key/value and the next key/value in Maps
本文介绍了如何获取地图中的上一个键/值和下一个键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for (Entry<Double, String> entry : map.entrySet()) {
Double key = entry.getKey();
String value = entry.getValue();
// double nextKey = ?
// String nextvalue = ?
// double prevKey = ?
// String prevValue = ?
}
在迭代时可以知道前一个元素和下一个元素是什么地图?
is it possible to know what the previous element and the next element while iterating the map?
推荐答案
你可以使用 NavigableMap
,其中 entrySet()
的迭代器返回条目 in升序键顺序:
You can use NavigableMap
for this, which entrySet()
's iterator return entries in ascending key order:
NavigableMap<Double, String> myMap = new TreeMap<>();
//...
for (Map.Entry<Double, String> e : myMap.entrySet()) {
Map.Entry<Double, String> next = myMap.higherEntry(e.getKey()); // next
Map.Entry<Double, String> prev = myMap.lowerEntry(e.getKey()); // previous
// do work with next and prev
}
每个条目检索都是O(logN),因此对于完全迭代,这不是最有效的方法。为了更有效,在迭代时只需记住最后3个条目,并使用1st作为prev,第2个作为current,第3个作为next,如 @Malt建议。
Every entry retrieval is O(logN), so for full iteration this is not the most effective approach. To be more effective, on iteration just remember last 3 entries, and use 1st as prev, 2nd as current and 3rd as next, as @Malt suggests.
这篇关于如何获取地图中的上一个键/值和下一个键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文