Reusing a stream when extra filtering is needed - Java

Viewed 334

The following code, in summary, is mean to filter through the first parameter for entities that are in the second parameter. And if a 'change' was specified in the second parameter, it should filter a narrower result.

When I run this I get an error of 'IllegalStateException: stream has already been operated upon or closed.'

Is there a way that I can reuse the same stream?
I have seen people implementing something like Supplier>, but I don't think that would work for this case. Or, I'm just not familiar enough with it to understand how I could use Supplier.

/**
     * Filters through DocumentAuditEntityListing to find existence of the entities
     * ActionEnum, ActionContextEnum, LevelEnum, & StatusEnum.
     *
     * @param audits A list of audits to search
     * @param toFind The audit entities to find
     * @return If entities found, return DocumentAudit, else null
     */
    public DocumentAudit verifyAudit(DocumentAuditEntityListing audits, DocumentAudit toFind) {
        //Filter for proper entities
        Stream stream = audits.getEntities().stream().filter(doc -> (
                doc.getAction().equals(toFind.getAction())) &&
                doc.getActionContext().equals(toFind.getActionContext()) &&
                doc.getLevel().equals(toFind.getLevel()) &&
                doc.getStatus().equals(toFind.getStatus()));

        //If changes were specified, filter further.
        if (toFind.getChanges() != null){
            stream.filter(change -> (toFind.getChanges().contains(change)));
        }

        return (DocumentAudit) stream.findFirst().orElse(null);
    }
3 Answers
Related