7

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?

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236

3 Answers3

5

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();
    ...
}
...
gpeche
  • 21,974
  • 5
  • 38
  • 51
2

Its much easier to have the previous value if you need to compare to consecutive values.

String pkey = null; 
String pvalue = null; 
for (Entry<String, String> entry : map.entrySet()) { 
    String key = entry.getKey(); 
    String value = entry.getValue(); 

    // do something with pkey/key and pvalue/value.

    pkey = key;
    pvalue = value;
} 
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Rather than for each loop, use an iterator.

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry entry = (Map.Entry)it.next();
    String key = entry.getKey();
    String value = entry.getValue();
    // do something
    // an event occurred 
    if (it.hasNext()) entry = (Map.Entry)it.next();
}
orangepips
  • 9,891
  • 6
  • 33
  • 57