use*_*267 6 java iterator java-8 java-stream
至于现在我在做:
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();
}
Run Code Online (Sandbox Code Playgroud)
有没有更简洁的方法来使用java8?
ass*_*ias 13
我发现你的方法存在两个问题:
HashMap例如,a 没有订单 - 所以你的方法实际上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();
Run Code Online (Sandbox Code Playgroud)
返回一个Optional.
好像你需要findFirst这里
Optional<Map.Entry<Item, Boolean>> firstEntry =
processedItem.entrySet().stream().findFirst();
Run Code Online (Sandbox Code Playgroud)
显然a HashMap没有顺序,所以findFirst可能会在不同的调用中返回不同的结果.可能更合适的方法适用findAny于您的情况.