在 Java 8 中用流替换嵌套 for 循环的正确方法是什么?

2022-01-22 00:00:00 java-8 java java-stream

在学习 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());

相关文章