【问题标题】:Nested ArrayList to single dimension将 ArrayList 嵌套到一维
【发布时间】:2019-01-23 08:24:49
【问题描述】:

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

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&lt;A&gt;)。我正在尝试映射此列表以获取所有名称。

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"]

【问题讨论】:

  • 使用flatMap.. 如果您在 map 步骤(else 返回一个流,而 if 部分返回一个字符串)。您是否将其收集到List&lt;Object&gt; 中?
  • 看看stackoverflow.com/questions/26684562/…会帮助你了解flatMap的使用

标签: java list arraylist


【解决方案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&lt;String&gt;,没有嵌套。

【讨论】:

    猜你喜欢
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2020-01-10
    相关资源
    最近更新 更多