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

前端 未结 2 1168
陌清茗
陌清茗 2020-12-09 06:04
for (Entry entry : map.entrySet()) { 
        Double key = entry.getKey(); 
        String value = entry.getValue(); 

        // double nextKe         


        
2条回答
  •  旧巷少年郎
    2020-12-09 06:17

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

    NavigableMap myMap = new TreeMap<>();
    
    //...
    
    for (Map.Entry e : myMap.entrySet()) {
        Map.Entry next = myMap.higherEntry(e.getKey()); // next
        Map.Entry 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.

提交回复
热议问题