Reputation: 1634
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 ?
Upvotes: 9
Views: 30943
Reputation: 120858
Seems like you need findFirst
here
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.
Upvotes: 8
Reputation: 328619
I see two problems with your method:
HashMap
, for example, has no order - so your method is really more of a getAny()
than a getNext()
.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
.
Upvotes: 21