gpt4 book ai didi

java - 流 'map'可以用于这样的处理吗?

转载 作者:行者123 更新时间:2023-12-02 07:50:56 30 4
gpt4 key购买 nike

可以使用 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()));

其中r.calcValue()计算新结果,然后将其放置在 map 中。

最佳答案

当然,您可以在此处使用Collectors#toMap()。假设 rTypes 包含 Report 实例:

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

(您确实有一个getReportType方法,对吧?:)

关于java - 流 'map'可以用于这样的处理吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593251/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com