0

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.

Alexis C.
  • 87,500
  • 20
  • 164
  • 172
deejo
  • 391
  • 1
  • 6
  • 13

1 Answers1

4

Something like this, obviously not compiled...

yourFruitList.stream()
       .collect(Collectors.groupingBy(
             Fruit::getName,
             Collectors.mapping(Fruit::getDesc, Collectors.toList())
       ))
Eugene
  • 110,516
  • 12
  • 173
  • 277