4

I have a class "First" which contains reference to Class "Second" as list. I am trying to achieve below block in Java 8 way by using Stream (or) flap Map (or) groupingBy

foreach(First a: listOfFirst){
    for (Second b: a.getSecondDetails()) {
        inputMap.put(b, a);
    }
}

I tried below simplified way

listOfFirst.stream()
    .flatMap(p -> p.getSecondDetails().stream())
    .collect(Collectors.toMap(p -> p, q -> q));

I am missing something here, please help me out

1
  • Please Elaborate this question Commented Mar 18, 2019 at 7:36

1 Answer 1

4

You need to "remember" the First instance corresponding to each Second instance. You can do it, for example, by creating Map.Entry instances:

Map<Second,First> result =
    listOfFirst.stream()
               .flatMap(p->p.getSecondDetails()
                            .stream()
                            .map(sec -> new SimpleEntry<>(sec,p))
               .collect(Collectors.toMap(Map.Entry::getKey,
                                         Map.Entry::getValue));
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I looking for !!

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.