java 获取 LinkedHashMap 中的下一项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4110045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get next item in LinkedHashMap?
提问by
I have the first key/value pair in a LinkedHashMap, which I get from a loop:
我在 LinkedHashMap 中有第一个键/值对,我从循环中得到:
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?
稍后,根据事件,我需要linkedHashMap 中的下一个键/值对。做这个的最好方式是什么?
采纳答案by gpeche
Get an iterator and use hasNext()
and next()
:
获取迭代器并使用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();
...
}
...
回答by Peter Lawrey
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;
}
回答by orangepips
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();
}