これをアプローチする1つの方法は、これを2段階操作として見ることです。最初のステップは、<Child, Parent>
ペアのストリームを作成し、groupingByを使用してそのストリームをMap<Child,Parent>
に縮小することです。
static class Parent{
String name;
List<Child> sons;
public Parent(final String name, final List<Child> sons) {
this.name = name;
this.sons = sons;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("sons", sons)
.toString();
}
}
static class Child{
public Child(final String name) {
this.name = name;
}
String name;
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.toString();
}
}
static void SonsToFathers(){
Child c1 = new Child("aa");
Child c2 = new Child("bb");
List<Parent> parents = ImmutableList.of(
new Parent("P1", ImmutableList.of(c1)),
new Parent("P2", ImmutableList.of(c1,c2)),
new Parent("P3", ImmutableList.of(c2)));
Map<Child,List<Parent>> childToParents = parents.stream()
.flatMap(p -> p.sons.stream()
.collect(Collectors.toMap(Function.identity(), s -> p))
.entrySet()
.stream())
.collect(Collectors.groupingBy(
Map.Entry::getKey,
mapping(Map.Entry::getValue, toList())));
System.out.println(childToParents);
}
コードを画像ではなくテキストとして送信してください。 –