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.

2
  • Possible duplicate of Java 8 List<V> into Map<K, V> Commented Nov 27, 2017 at 12:40
  • 1
    @nullpointer I would say this is about <K, V> into Map<K, List<V>> Commented Nov 27, 2017 at 14:12

1 Answer 1

5

Something like this, obviously not compiled...

yourFruitList.stream()
       .collect(Collectors.groupingBy(
             Fruit::getName,
             Collectors.mapping(Fruit::getDesc, Collectors.toList())
       ))
Sign up to request clarification or add additional context in comments.

1 Comment

@Hadi no worries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.