deejo
deejo

Reputation: 451

Java 8 Streams API - List to Map - Merge keys

I have a list of Fruit objects where every Fruit has a 'name' and 'desc'. This list of Fruits will contain duplicate 'name' with different 'desc'. i.e.

{"apple","its red"},{"banana","its yellow"},{"apple", "its hard"}

Now, I want to use Java 8 Streams API to iterate over this list of Fruits and map them into a MAP such that key is 'name' and must not contain duplicates.

Output should be:

key - "apple", value - List of desc i.e.  {"its red","its hard"}
key - "banana", value - {"its yellow"}

Please guide.

Upvotes: 0

Views: 838

Answers (1)

Eugene
Eugene

Reputation: 120968

Something like this, obviously not compiled...

yourFruitList.stream()
       .collect(Collectors.groupingBy(
             Fruit::getName,
             Collectors.mapping(Fruit::getDesc, Collectors.toList())
       ))

Upvotes: 5

Related Questions