可以使用流"地图"进行此类处理吗?

use*_*r_x 2 java dictionary java-8 java-stream

这可以通过Stream | Map完成,这样我就不需要将结果放在外部HashMap中,而是使用.collect(Collectors.toMap(...))收集结果; ?

Map<ReportType, Long> rep = new HashMap<>(); // result is here
Arrays.stream(rTypes).forEach(r -> rep.put(r.reportType, r.calcValue()));
Run Code Online (Sandbox Code Playgroud)

在哪里r.calcValue()计算新结果,然后放在地图中.

Mat*_*all 6

当然,你可以Collectors#toMap()在这里使用.假设rTypes包含Report实例:

Map<ReportType, Long> rep = Arrays.stream(rTypes)
  .collect(Collectors.toMap(Report::getReportType, Report::calcValue));
Run Code Online (Sandbox Code Playgroud)

(你有一个getReportType方法,对不对?:)


Tun*_*aki 5

是的,它可以这样做,假设r.calcValue()返回一个Long:

Map<ReportType, Long> rep = Arrays.stream(rTypes)
                      .collect(Collectors.toMap(r -> r.reportType, r -> r.calcValue()));
Run Code Online (Sandbox Code Playgroud)