Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...