有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java嵌套ArrayList到单个维度

我有一些代码看起来像这样

class A {}
class B extends A {
    private String name; // assume there's a getter
}
class C extends A {
    private List<B> items = new ArrayList<>(); // assume a getter
}

在另一个类中,我有一个ArrayList(ArrayList<A>)。我正试图绘制这个列表,以获得所有的名字

List<A> list = new ArrayList<>();
// a while later
list.stream()
    .map(a -> {
        if (a instanceof B) {
            return ((B) a).getName();
        } else {
            C c = (C) a;
            return c.getItems().stream()
                .map(o::getName);
        }
    })
    ...

这里的问题是,我最终得到了类似这样的东西(用于视觉目的的JSON)

["name", "someName", ["other name", "you get the idea"], "another name"]

我如何映射此列表,以便最终得到以下结果

["name", "someName", "other name", "you get the idea", "another name"]

共 (1) 个答案

  1. # 1 楼答案

    使用flatMap

    list.stream()
        .flatMap(a -> {
            if (a instanceof B) {
                return Stream.of(((B) a).getName());
            } else {
                C c = (C) a;
                return c.getItems().stream().map(o::getName);
            }
        })
        ...
    

    这将生成所有名称的Stream<String>,而不嵌套