在 Java 8 中用流替换嵌套 for 循环的正确方法是什么? [英] What is the proper way of replacing a nested for loop with streams in Java 8?

查看:28
本文介绍了在 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 循环的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆