所以一種方法來看待這是一個兩步操作。第一步是建立一對<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);
}
將您的代碼發佈爲文本,而不是圖片。 –