Home > Mobile >  Split a single stream into two lists
Split a single stream into two lists

Time:10-15

Given a single stream Stream<Acknowledgement> mappedRecords, how can I split it into two two lists based on two filters? Here is my attempt:

List<Acknowledgement> summaryList =
    mappedRecords
        .filter(x -> x.getReportType().equals(summaryReportType))
        .collect(Collectors.toList());

List<Acknowledgement> detailList =
    mappedRecords
        .filter(x -> x.getReportType().equals(detailReportType))
        .collect(Collectors.toList());

This code produces an error:

java.lang.IllegalStateException: stream has already been operated upon or closed

CodePudding user response:

The specific filters you describe suggest a pretty clean way to do it, actually:

Map<ReportType, List<Acknowledgement>> lists = mappedRecords.collect(
   Collectors.groupingBy(x -> x.getReportType()));
List<Acknowledgement> summaryList = lists.get(summaryReportType);
List<Acknowledgement> detailList = lists.get(detailReportType);
  • Related