代码之家  ›  专栏  ›  技术社区  ›  Spedwards

嵌套ArrayList到一维

  •  2
  • Spedwards  · 技术社区  · 6 年前

    我有一些像这样的代码。

    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<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 回复  |  直到 6 年前
        1
  •  4
  •   Eran    6 年前

    使用 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> 所有的名字,没有嵌套。