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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27174700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:20:26  来源:igfitidea点击:

What is the proper way of replacing a nested for loop with streams in Java 8?

javajava-8java-stream

提问by Pierre Henry

While learning Java 8 streams and lambas, I tried to replace the following nested for loops with streams :

在学习 Java 8 流和 labas 时,我尝试用流替换以下嵌套的 for 循环:

List<Long> deskIds = new ArrayList<>();
for(ProvidedService memberService : service.getAllNodesDepthFirst()){
   for(Desk d : memberService.getDesks()){
     deskIds.add(d.getId());
   }
}

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.

该循环迭代“ProvidedService”对象的列表,对于每个对象,迭代“Desk”对象的列表属性,并将“Id”字段提取到列表中。

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 ?

这是正确/最佳的方法吗?或者有没有办法在没有第二个嵌套流的情况下做到这一点?

回答by assylias

I would probably write it like this:

我大概会这样写:

List<Long> deskIds = service.getAllNodesDepthFirst().stream()
                                          .flatMap(p -> p.getDesks().stream())
                                          .map(Desk::getId)
                                          .collect(toList());