gpt4 book ai didi

java - 使用 java8 lambdas 创建新列表

转载 作者:行者123 更新时间:2023-11-30 06:48:35 24 4
gpt4 key购买 nike

在下面的代码中,我使用嵌套的 for 循环创建了一个新的“flatChildren”集合。我如何通过使用 lambdas 来解决这个问题?

注意:不能更改父类和子类。

static class Parent {
String name;
List<Child> children;

Parent(String name, List<Child> children) {
this.name = name;
this.children = children;
}
}

static class Child {
String name;

Child(String name) {
this.name = name;
}
}

static class FlatChild {
String parentName;
String name;

public FlatChild(String parentName, String name) {
this.parentName = parentName;
this.name = name;
}

@Override
public String toString() {
return "FlatChild{" +
"parentName='" + parentName + '\'' +
", name='" + name + '\'' +
'}';
}
}

public static void main(String[] args) {
final List<Parent> parents = Arrays.asList(
new Parent("1",
Arrays.asList(new Child("a"), new Child("b"))),
new Parent("1",
Arrays.asList(new Child("c"))),
new Parent("2",
Arrays.asList(new Child("e"), new Child("f"))));

List<FlatChild> flatChildren = new ArrayList<>();
for (Parent parent : parents) {
for (Child child : parent.children) {
flatChildren.add(new FlatChild(parent.name, child.name));
}
}
// does not work, cannot access p in the map function.
// final Stream<FlatChild> flatChildStream = parents.stream()
// .flatMap(p -> p.children.stream()).map(c -> new FlatChild(p.name, c.name));

System.out.println(flatChildren);
}

在此先感谢您的帮助。

最佳答案

map Child 到传递给 flatMap 的内部 Stream 中的 FlatChild >:

final Stream<FlatChild> flatChildStream = 
parents.stream()
.flatMap(p -> p.children
.stream()
.map(c -> new FlatChild(p.name, c.name)));

关于java - 使用 java8 lambdas 创建新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44041907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com