2

I have a class Person with constructor

Person(Fruit... favoriteFruits) {}

And 3 objects (let's say)

Person A = new Person(Apple);
Person B = new Person(Banana, Papaya);
Person C = new Person(Pineapple, Orange);

and a method in class Person Fruit[] getFavouriteFruits(){}

Using streams, I am trying to convert this into Map

Expected Output: Map of ((Apple, A), (Banana, B), (Papaya, B), (Pineapple, C), (Orange, C))

Not sure how to flatten the Array of Fruits into a stream

0

1 Answer 1

2

I hope I don't have typos. The idea is to transform the List<Person> to a Stream of all the pairs of (Person,Fruit) and group them by Fruit.

Map<Fruit,List<Person>> map =
  List.of(A,B,C)
      .stream()
      .flatMap(p -> Arrays.stream(p.getFavouriteFruits())
                          .map(f -> new SimpleEntry<Person,Fruit>(p,f)))
      .collect(Collectors.groupingBy(Map.Entry::getValue,
                                     Collectors.mapping(Map.Entry::getKey,
                                                        Collectors.toList())));

SimpleEntry is java.util.AbstractMap.SimpleEntry.

Sign up to request clarification or add additional context in comments.

1 Comment

Or not swapping <Person,Fruit> to <Fruit, List<Person>, one can create entries such as new SimpleEntry<Fruit,Person>(f,p)` which might read easier.

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.