如何使用 JAVA 8 从地图中获取第一个键值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43627091/
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
How to get the first key value from map using JAVA 8?
提问by user3407267
As for now I am doing :
至于现在我在做什么:
Map<Item, Boolean> processedItem = processedItemMap.get(i);
Map.Entry<Item, Boolean> entrySet = getNextPosition(processedItem);
Item key = entrySet.getKey();
Boolean value = entrySet.getValue();
public static Map.Entry<Item, Boolean> getNextPosition(Map<Item, Boolean> processedItem) {
return processedItem.entrySet().iterator().next();
}
Is there any cleaner way to do this with java8 ?
有没有更干净的方法可以用 java8 做到这一点?
回答by assylias
I see two problems with your method:
我发现你的方法有两个问题:
- it will throw an exception if the map is empty
- a
HashMap
, for example, has no order - so your method is really more of agetAny()
than agetNext()
.
- 如果地图为空,它将抛出异常
HashMap
例如,a没有顺序 - 所以你的方法实际上getAny()
比 a更像是agetNext()
。
With a stream you could use either:
对于流,您可以使用:
//if order is important, e.g. with a TreeMap/LinkedHashMap
map.entrySet().stream().findFirst();
//if order is not important or with unordered maps (HashMap...)
map.entrySet().stream().findAny();
which returns an Optional
.
它返回一个Optional
.
回答by Eugene
Seems like you need findFirst
here
好像你需要findFirst
这里
Optional<Map.Entry<Item, Boolean>> firstEntry =
processedItem.entrySet().stream().findFirst();
Obviously a HashMap
has no order, so findFirst might return a different result on different calls. Probably a more suitable method would be findAny
for your case.
显然 aHashMap
没有顺序,因此 findFirst 可能会在不同的调用中返回不同的结果。可能更适合findAny
您的情况的方法。