我正在努力退回仅包含 item.baz.fooz == 'snafu' 的项目。我已将下面的代码和源代码匿名化。您的帮助将不胜感激。 我的数据来源:
{
"data": {
"searches": [
{
"apples": [
{
"pears": [
{
"sets": [
{
"items": [
{
"baz": {
"fooz": {
"unit": "snafu"
}
}
}
]
}
]
}
]
}
]
}
]
}
}
我失败的代码:
List<Item> items =
response.data.searches.stream()
.flatMap(
search -> search.apples.forEach(
apple -> apple.pears.forEach(
pear -> pear.sets.forEach(
set -> set.items.stream()
.filter(item -> item.baz.fooz.unit.equals("snafu"))
.collect(Collectors.toList())))));
失败的是(除其他外):
Incompatible type. Required List<Foo> but 'flatmap' was inferred to Stream<R>: no instances of type variable R List<Foo>
最佳答案
不要使用forEach
,你需要多个flatMap
:
List<Item> snoozles =
response.data
.searches
.stream() // Stream<Search>
.flatMap(search -> search.apples.stream()) // Stream<Apple>
.flatMap(apple -> apple.pears.stream()) // Stream<Pear>
.flatMap(pear -> pear.sets.stream()) // Stream<Set>
.flatMap(set -> set.items.stream()
.filter(item -> item.baz.fooz.unit.equals("snafu"))) // Stream<Item>
.collect(Collectors.toList()); // List<Item>
或者(如 Holger 所建议的):
List<Item> snoozles =
response.data
.searches
.stream() // Stream<Search>
.flatMap(search -> search.apples.stream()) // Stream<Apple>
.flatMap(apple -> apple.pears.stream()) // Stream<Pear>
.flatMap(pear -> pear.sets.stream()) // Stream<Set>
.flatMap(set -> set.items.stream()) // Stream<Item>
.filter(item -> item.baz.fooz.unit.equals("snafu")) // Stream<Item>
.collect(Collectors.toList()); // List<Item>
关于java - 我正在尝试通过使用 Java 8 流遍历嵌入式列表来返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56439928/