Individual map with Java streams

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; } /** * @return universally unique identifier */ 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?

+7
source share
3 answers

Use Collectors#toMap(Function, Function) , generating the key of each Item uuid and Item as the value itself.

 public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) { return itemStream.collect(Collectors.toMap(Item::getUuid, Function.identity())); } 

Note from javadoc

If the displayed keys contain duplicates (according to Object.equals(Object) ), a IllegalStateException is thrown when the collection is performed. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead.

+9
source

groupingBy() collects elements (plural, like List ) using a key.

Do you want toMap() :

 public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) { return itemStream.collect(toMap(Item::getUuid, Function.identity())); } 
+1
source

Maybe try

 itemStream.stream().collect(toMap(Item::getUuid,Functions.identity()); 
-1
source

All Articles