[英]How to get the first key value from map using JAVA 8?
至於現在我在做:
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();
}
有沒有更簡潔的方法來使用java8?
我發現你的方法存在兩個問題:
HashMap
沒有順序 - 所以你的方法實際上更像是getAny()
不是getNext()
。 使用流可以使用以下任一方式:
//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();
返回一個Optional
。
好像你在這里需要findFirst
Optional<Map.Entry<Item, Boolean>> firstEntry =
processedItem.entrySet().stream().findFirst();
顯然HashMap
沒有順序,因此findFirst可能會在不同的調用上返回不同的結果。 可能是一個更合適的方法是findAny
對你的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.