gpt4 book ai didi

java - 流供应商收到错误 'stream has already been operated upon or closed'

转载 作者:行者123 更新时间:2023-11-29 08:20:50 25 4
gpt4 key购买 nike

即使我正在为我的流使用 Supplier 并在每次我想检索我的 strem 并对其执行终端操作时使用 Supplier.Get() ,我仍然得到“流已经被操作或关闭”异常(exception)。谁能看看我的代码并提出我做错了什么?

抛出异常的方法:

private static void printMyDetails(Supplier<Stream<Result>> mySupplier, String myStatus) {
checkNotNull(mySupplier);
checkArgument(isNotEmpty(myStatus), "Invalid My status");

if (mySupplier.get().noneMatch(result -> true)) { //<-This is where the exception is thrown
if (log.isInfoEnabled()) {
log.info("Number of My with status '{}': {}", My, 0);
}
} else {
log.info("Number of My with status '{}': {}", myStatus, mySupplier.get().count());
log.info("Details of My(s) with status: '{}'", myStatus);
mySupplier.get().sorted().forEach(Utils::printMyNameAndDetails);
}
}

调用上述方法的地方:

rb.keySet().stream().filter(key -> containsIgnoreCase(key, "status")).map(rb::getString)
.filter(StringUtils::isNotEmpty).forEach(status -> {
var resultsWithExpectedStatusSupplier = requireNonNull(getResultsWithExpectedStatusSupplier(results, status));
resultsWithExpectedStatusSupplier.ifPresentOrElse(streamSupplier -> printMyDetails(streamSupplier, status), () -> {
if (log.isInfoEnabled())
log.info("0 My with status: {}", status);
});
});

流供应商:

private static Optional<Supplier<Stream<Result>>> getResultsWithExpectedStatusSupplier(
@NotNull List<Result> results, @NotNull String expectedStatus) {
checkArgument(!results.isEmpty(), "Results list is empty");
checkArgument(isNotEmpty(expectedStatus), "Invalid expected status");

var resultStreamWithExpectedStatus = requireNonNull(results.stream().filter(result -> ofNullable(result).map(Result::getStatus)
.allMatch(s -> isNotEmpty(s) && s.equalsIgnoreCase(expectedStatus))));
return resultStreamWithExpectedStatus.count() == 0 ? Optional.empty() : Optional.of(() -> resultStreamWithExpectedStatus);
}

最佳答案

一般问题正如 Christian Ullenboom 所说:流已被消耗。您的代码中的确切位置是在方法 getResultsWithExpectedStatusSupplier 中对 resultStreamWithExpectedStatus.count() 的调用,因为 Stream.count 是一个缩减/终端消耗流的操作。

如示例中所述this answer ,您无法在不消耗流的情况下获得流的大小。通过将过滤后的项目存储在集合中(例如 Collectors.toList)、查询那里的大小并返回集合本身而不是流来修复它?

附带说明一下,我认为您过度滥用了 Optional。代码可以更简单地传递空流(或者甚至更好:传递一个空的、经过过滤的集合)。

关于java - 流供应商收到错误 'stream has already been operated upon or closed',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58709911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com