使用java8 lambdas创建新列表

时间:2017-05-18 08:00:41

标签: java

在下面的代码中,我创建了一个新的'flatChildren'使用嵌套for循环。我如何通过使用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);
}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

map内部Child的{​​{1}}到FlatChild传递给Stream

flatMap