【发布时间】: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<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"]
【问题讨论】:
-
使用
flatMap.. 如果您在 map 步骤(else 返回一个流,而 if 部分返回一个字符串)。您是否将其收集到List<Object>中? -
看看stackoverflow.com/questions/26684562/…会帮助你了解flatMap的使用