Having a small problem using the Stream API to get a one-to-one mapping. Basically, let's say you have a class.
public class Item { private final String uuid; private Item(String uuid) { this.uuid = uuid; } public String getUuid() { return uuid; } }
I need Map<String, Item> for a convenient search. But with a Stream<Item> there is no easy way to achieve this Map<String, Item> .
Obviously, Map<String, List<Item>> does not matter:
public static Map<String, List<Item>> streamToOneToMany(Stream<Item> itemStream) { return itemStream.collect(groupingBy(Item::getUuid)); }
This is a safer, more general case, but we know in this situation that there will always be only one to one. I cannot find anything that compiles, although I specifically tried to disable the downstream parameter before Collectors.groupingBy . Sort of:
// DOESN'T COMPILE public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) { return itemStream.collect(groupingBy(Item::getUuid, Function.identity())); }
What am I missing?
source share