user2781389 user2781389 - 1 year ago 122
Java Question

Lookup enum value in a map to initialise list

Given I have the following

Map
and call to
writeMetadata(...)
:

Map<Report, TransferStatus> transferStatusMap = sftpService.transfer(reportDeliverables);

dbMetadataWriter.writeMetadata(successReports);


ENUM
as:

public enum TransferStatus {
SUCCESS,
FAILURE
}


Firstly, how can I create the
successReport
list with all
Report
with status
TransferStatus.SUCCESS
with Java 8?

Secondly, before call to
dbMetadataWriter.writeMetadata(successReports);
there should be a check to see if any values with success exist.

and finally, in general how should failed transfers be handled? Practically, what is best practice?

Answer Source
 List<Report> successReports = transferStatusMap.entrySet()
          .stream()
          .filter(e -> e.getValue() == TransferStatus.SUCCESS)
          .map(Entry::getKey)
          .collect(Collectors.toList());

 if(!reports.isEmpty()){
     dbMetadataWriter.writeMetadata(successReports);
 }

Or you could collect them both to a Map:

Map<TransferStatus, List<Report>> map = 
     transferStatusMap.entrySet()
                      .stream()
                      .collect(Collectors.groupingBy(
                            Entry::getValue,
                            Collectors.mapping(Entry::getKey, Collectors.toList()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download