使用Java 8 Stream返回没有副作用的Map的Map

时间:2019-02-07 01:48:41

标签: java java-8 hashmap java-stream

我如何将带有密钥eServiceReportsMapByBatchFile的{​​{1}}放入/添加到oldReportId中而没有副作用?

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;

谢谢。

2 个答案:

答案 0 :(得分:5)

您最期待Collectors.toMap可以用作:

return reports.stream()
        .collect(Collectors.toMap(report -> report.getOldId(),
                        report -> {
                    // batch processing for eServiceReportsMapByBatchFile
                            return eServiceReportsMapByBatchFile;
                }));

答案 1 :(得分:3)

由于您在stream上调用reports,所以我认为它是某种类型的集合;在这种情况下,您的副作用没有任何问题。请注意,someCollection.stream().forEachsomeCollection.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
       ))