Converting list object into custom Map using Java 8 stream object

Arun :

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

Eran :

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));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92297&siteId=1