gpt4 book ai didi

java - 嵌套 ArrayList 到单维

转载 作者:行者123 更新时间:2023-11-30 06:41:56 24 4
gpt4 key购买 nike

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

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 :

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

关于java - 嵌套 ArrayList 到单维,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54322829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com