简体   繁体   中英

Can stream 'map' be used for such processing?

Can this be done with Stream|Map so that I wouldn't need to place result in external HashMap, but collect result with .collect(Collectors.toMap(...)); ?

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

Where r.calcValue() calculates the new result, that is placed then in map.

Sure, you can use Collectors#toMap() here. Assuming rTypes contains Report instances:

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

(You do have a getReportType method, right? :)

Yes, it can be done like this, assuming r.calcValue() returns a Long :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM