Having a little trouble using the Stream API to get a one to one mapping. Basically, say you've got a class.
public class Item {
private final String uuid;
private Item(String uuid) {
this.uuid = uuid;
}
/**
* @return universally unique identifier
*/
public String getUuid() {
return uuid;
}
}
I'd like a Map<String, Item>
for easy look up. But given a Stream<Item>
there doesn't seem a simple way to arrive at that Map<String, Item>
.
Obviously, Map<String, List<Item>>
ain't no thing:
public static Map<String, List<Item>> streamToOneToMany(Stream<Item> itemStream) {
return itemStream.collect(groupingBy(Item::getUuid));
}
That's the safer more general case, but we do know in this situation that there will only ever be one-to-one. I can't find anything that compiles though -- I've specifically been trying to muck with the downstream
parameter to Collectors.groupingBy
. Something like:
// DOESN'T COMPILE
public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) {
return itemStream.collect(groupingBy(Item::getUuid, Function.identity()));
}
What am I missing?