简体   繁体   中英

Converting list object into custom Map using Java 8 stream object

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM