Reputation: 451
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
Reputation: 120968
Something like this, obviously not compiled...
yourFruitList.stream()
.collect(Collectors.groupingBy(
Fruit::getName,
Collectors.mapping(Fruit::getDesc, Collectors.toList())
))
Upvotes: 5