【发布时间】:2018-05-12 09:44:25
【问题描述】:
总而言之,以下代码旨在通过第一个参数过滤第二个参数中的实体。如果在第二个参数中指定了“更改”,它应该过滤更窄的结果。
当我运行它时,我收到“IllegalStateException:流已被操作或关闭”的错误。
有没有办法可以重复使用相同的流?
我见过人们实施类似供应商>的东西,但我认为这不适用于这种情况。或者,我只是对它不够熟悉,无法理解如何使用 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);
}
【问题讨论】:
-
流有终端和非终端方法。像 map 和 filter 这样的非终端方法是惰性的,这意味着它们实际上在调用终端方法之前不会做任何事情。这意味着您只需要按照@Kayaman 的说明添加过滤器来“附加”到流中,但您不会“重新使用”流,因为在您调用
findFirst().orElse(null)之前它还没有被“使用” -
好问题,从错误消息中理解并不是那么简单。基本上你只消费你的流一次,但这不是错误消息所说的......stackoverflow.com/a/47548077/1059372
标签: java java-8 java-stream audit