java - 我正在尝试通过使用 java 8 流遍历嵌入列表来返回数据
问题描述
我正在努力返回仅包含 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>
或者(正如霍尔格建议的那样):
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>
推荐阅读
- python - 用 numpy.mean 分组
- c# - () => 的目的与直接获取属性
- css - 添加类以在没有javascript的情况下更改div内的位置背景图像
- javascript - 这个(6 <= N <= 20)和这个(N >= 6 && N <=20)之间的区别?
- arm - µVision IDE 上的 TI TM4C129E 性能分析
- java - 我可以在 JAVA 中的非赋值情况下使用条件运算符吗?
- excel - 如何获得具有功率枢轴的百分比字段?
- woocommerce - 对最后缺货的产品进行分类
- php - 在刀片模板中组织组件的最佳方式
- javascript - JavaScript AWS Cognito 连接问题“NetworkError”