Java 8 Streams get original object after filtering map

Viewed 328

I have to get the receipt id for not paid invoices. Orders has multiple receipts and receipts has invoices. I am using Java 8 stream. From receipts stream, I am able to get only invoices list, but I want to get receipt id for not paid invoices

Here is my code:

List<Invoice> invoicesNotPaid = receipts.stream()
            .map(ReceiptsVO::getInvoices)
            .flatMap(List::stream)
            .map(inv -> Invoice.builder().status(InvoiceStatus.getStatus(inv.getStatus().name())).build())
            .filter(Invoice::hasNotBeenPaid).collect(Collectors.toList());

after the final filter I am getting invoices only, I am not able to get the original receipts object reference. I have to do some thing like below, after checking the receipts against not paid invoices.

receipts -> receipt.getReceiptId()

How to get the receipt Id for not paid invoices?

2 Answers

Instead of throwing away data with flatMap, do a filter with an inner stream:

List<Invoice> invoicesNotPaid = receipts.stream()
            .filter(receipt -> receipt.getInvoices().stream().anyMatch(inv -> !hasBeenPaid(inv))
            .collect(Collectors.toList());

you can stream the receipts and then check at least one invoive in receipt is not paid and then collect those receipt id's

List<Integer> receiptIdNotPaid = receipts.stream()
     .filter(receipt-> receipt.getInvoices().stream()
              .map(inv->Invoice.builder().status(InvoiceStatus.getStatus(inv.getStatus().name())).build())
              .anyMatch(Invoice::hasNotBeenPaid))
     .map(Receipt::getReceiptId)
     .collect(Collectors.toList());
Related