我有一些像这样的代码。
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"]