java - 流 - 过滤器中的 anyMatch 产生 IllegalStateException
问题描述
我正在尝试遍历两个列表,我得到一个IllegalStateException: stream has already been operated upon or closed
file().forEach(line -> {
boolean match = ordersSupplier.get().anyMatch(order -> order == line.id);
if (match) {
//do something;
}
});
我知道 anyMatch 是终端操作,这就是我收到此错误的原因。我可以使用行的 id 参数化 Supplier für anyMatch 吗?任何想法?
解决方案
使用 Stream API收集 aSet
和您的行中的订单 ID 。filter
然后,您可以在forEach
.
Set<String> orderIds = ordersSupplier.get().collect(toSet());
file().stream()
.filter(l -> orderIds.contains(l.id))
.forEach(
line -> {
//do something;
});