Get next item in LinkedHashMap?

user375566 picture user375566 · Nov 5, 2010 · Viewed 16k times · Source

I have the first key/value pair in a LinkedHashMap, which I get from a loop:

for (Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    //put key value to use
    break;
}

Later on, based on an event, I need the next key/value pair in the linkedHashMap. What is the best way to do this?

Answer

gpeche picture gpeche · Nov 5, 2010

Get an iterator and use hasNext() and next():

...
Iterator<Entry<String, String>> it = map.entrySet().iterator();
if (it.hasNext()) {
    Entry<String, String> first = it.next();
    ...
}
...
if (eventHappened && it.hasNext()) {
    Entry<String, String> second = it.next();
    ...
}
...