Reputation: 68
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
Upvotes: 4
Views: 1129
Reputation: 394146
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));
Upvotes: 4