Get next item in LinkedHashMap?
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?
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();
...
}
...
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;
}
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();
}
精彩评论