我正在查看一个深度嵌套 for 循环的代码,我想使用 java-8 流以纯函数形式重写它,但我看到的是每个级别都需要多个值,而我不需要确定如何以干净的方式解决这个问题。
List<Report> reports = new ArrayList();
for (DigitalLogic dl : digitalLogics){
for (Wizard wiz : dl.getWizards){
for(Vice vice : wiz.getVices()){
reports.add(createReport(dl, wiz, vice));
}
}
}
//
Report createReport(DigitalLogic dl, Wizard wiz, Vice vice){
//Gets certain elements from all parameters and creates a report object
}
我的真实案例场景比这复杂得多,但我想知道是否有一种更干净的纯函数方式使用流来编写它。以下是我的初步尝试
List<Report> reports = new ArrayList();
digitalLogics.stream()
.map(dl -> dl.getWizards())
.flatMap(List::stream())
.map(wiz -> wiz.getVices())
.flatMap(List::stream())
.forEach(vice -> reports.add(createReport(?, ?, vice));
显然,我丢失了 DigitalLogic 和 Wizard 引用资料。
最佳答案
我将使用 forEach
方法,因为 stream
解决方案使这个变得复杂
List<Report> reports = new ArrayList<>();
digitalLogics.forEach(dl->dl.getWizards()
.forEach(wiz->wiz.getVices()
.forEach(v->reports.add(createReport(dl, wiz, v)))));
关于java - 将嵌套 for 循环转换为维护数据的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978914/