java 如何在地图中获取上一个键/值和下一个键/值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30099237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:28:45  来源:igfitidea点击:

How to get the previous key/value and the next key/value in Maps

javadictionary

提问by d_low

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?

迭代地图时是否可以知道前一个元素和下一个元素是什么?

回答by Alex Salauyou

You can use NavigableMapfor this, which entrySet()'s iterator return entries in ascending key order:

您可以NavigableMap为此使用它,它entrySet()的迭代器以键升序返回条目:

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
}

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.

每个条目检索都是 O(logN),因此对于完整迭代,这不是最有效的方法。为了更有效,在迭代时只记住最后 3 个条目,并使用第一个作为上一个,第二个作为当前使用,第三个作为下一个,正如@Malt 建议的那样

回答by Kayaman

A TreeMapis an OrderedMapand a NavigableMapand will allow you to iterate forward and backward, allowing you to access previous and next keys with lowerKey()and higherKey()respectively. However it might not be the best solution.

一个TreeMap的OrderedMapNavigableMap,将让你与迭代前进,后退,让你访问一个和下一个键lowerKey()higherKey()分别。但是,这可能不是最佳解决方案。

Can you describe the actual problem you're trying to solve, and we can give you a more fitting solution?

你能描述一下你试图解决的实际问题,我们可以给你一个更合适的解决方案吗?