What is the proper way of replacing a nested for loop with streams in Java 8?(在 Java 8 中用流替换嵌套 for 循环的正确方法是什么?)
问题描述
在学习 Java 8 流和 Lambas 时,我尝试将以下嵌套的 for 循环替换为流:
While learning Java 8 streams and lambas, I tried to replace the following nested for loops with streams :
List<Long> deskIds = new ArrayList<>();
for(ProvidedService memberService : service.getAllNodesDepthFirst()){
for(Desk d : memberService.getDesks()){
deskIds.add(d.getId());
}
}
循环迭代ProvidedService"对象的列表,并为每个对象迭代Desk"对象的列表属性,并将Id"字段提取到列表中.
The loop iterates a list of 'ProvidedService' objects, and for each one, iterates over a list property of 'Desk' objects, and extracts the 'Id' field to a list.
我使用流想出了以下代码:
I came up with the following code using streams :
List<Long> deskIds = new ArrayList<>();
service.getAllNodesDepthFirst().stream().forEach(srv -> {
deskIds.addAll(srv.getDesks().stream().map(Desk::getId).collect(Collectors.toList()));
});
这是正确/最佳的方法吗?或者有没有办法在没有第二个嵌套流的情况下做到这一点?
Is it the proper/optimal way to do it ? Or is there a way to do this without the second nested stream ?
推荐答案
我大概会这样写:
List<Long> deskIds = service.getAllNodesDepthFirst().stream()
.flatMap(p -> p.getDesks().stream())
.map(Desk::getId)
.collect(toList());
这篇关于在 Java 8 中用流替换嵌套 for 循环的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 8 中用流替换嵌套 for 循环的正确方法是什么?
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
