Home > Software design >  Collecting Stream<Map> into a Map<>
Collecting Stream<Map> into a Map<>

Time:12-12

How can the below Stream<Map> be collected into a Map<String, Product> or com.google.common.collect.Multimap<String, Product>?

 Stream<Map<String, Product>> val 

CodePudding user response:

A Stream is what it says on the tin - an incoming stream of elements, whose type is <T>. That means, that a Stream<Map<String, Product>> is an incoming stream of maps. You can't just collect that into one single map without throwing away some potential elements.

Instead, you can collect it into a list of maps: List<Map<String, Product>> mapList = theStream.toList();

If you do want to only get one element from the stream, you can call .findFirst().get() to get the first element from the stream, .filter(...).findFirst().get() to find the first element that meets a certain condition, etc.

  • Related