使用Java8流返回没有副作用的地图地图
如何使用键使用Java8流返回没有副作用的地图地图,java,java-8,hashmap,java-stream,Java,Java 8,Hashmap,Java Stream,如何使用键oldReportId将eServiceReportsMap放入/添加到eServiceReportMap,而不产生副作用 Map<String, Map<String, Set<EServiceReport>>> eServiceReportMap = new HashMap<>(); reports.forEach(report -> { String oldReportId = report.getOldId();
oldReportId
将eServiceReportsMap
放入/添加到eServiceReportMap
,而不产生副作用
Map<String, Map<String, Set<EServiceReport>>> eServiceReportMap = new HashMap<>();
reports.forEach(report -> {
String oldReportId = report.getOldId();
Map<String, Set<EServiceReport>> eServiceReportsMapByBatchFile = // processing of batch files
...
eServiceReportMap.put(oldReportId, eServiceReportsMapByBatchFile);
});
return eServiceReportMap;
Map eServiceReportMap=new HashMap();
报告。forEach(报告->{
字符串oldReportId=report.getOldId();
Map eServiceReportsMapByBatchFile=//批处理文件的处理
...
eServiceReportMap.put(oldReportId,eServiceReportsMapByBatchFile);
});
返回eServiceReportMap;
也就是说,我希望它变成这样:
return reports.stream()
.map(report -> {
String oldReportId = report.getOldId();
Map<String, Set<EServiceReport>> eServiceReportsMapByBatchFile = // processing of batch files
...
// I don't know how and what to return here
}).collect(// I don't know what to do here);
return reports.stream()
.map(报告->{
字符串oldReportId=report.getOldId();
Map eServiceReportsMapByBatchFile=//批处理文件的处理
...
//我不知道该怎么回去,也不知道该怎么回去
}).collect(//我不知道在这里做什么);
谢谢。您最期待的是
收藏家。toMap
可以用作:
return reports.stream()
.collect(Collectors.toMap(report -> report.getOldId(),
report -> {
// batch processing for eServiceReportsMapByBatchFile
return eServiceReportsMapByBatchFile;
}));
由于您在
报告
上调用流
,因此我假定它是某种类型的集合;在这种情况下,你的副作用没有问题。请注意,someCollection.stream().forEach
和someCollection.forEach
是非常不同的东西,您完全可以使用someCollection::forEach
-这只是一个简单的内部循环
您可以将其转换为流解决方案,但其可读性将大大降低:
reports.stream()
.map(r -> {
String oldReportId = report.getOldId();
Map<String, Set<EServiceReport>> eServiceReportsMapByBatchFile =....
return new SimpleEntry<>(oldReportId, eServiceReportsMapByBatchFile);
})
.collect(Collectors.toMap(
Entry::getKey,
Entry::getValue,
(left, right) -> right; // to match whatever you had until now
))
reports.stream()
.map(r->{
字符串oldReportId=report.getOldId();
Map eServiceReportsMapByBatchFile=。。。。
返回新的SimpleEntry(oldReportId、eServiceReportsMapByBatchFile);
})
.collect(collector.toMap)(
条目::getKey,
条目::getValue,
(左,右)->right;//匹配到目前为止您拥有的任何内容
))
什么是报告
?