我正在努力返回仅包含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
s:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句