试图更新CompletableFuture变量,但出现错误:从lambda表达式引用的局部变量必须是final或实际上是


public CompletableFuture<String> description() {
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> "Search for: " + this.stop + " <-> " + name + ":n")
.thenApply(x -> x += "From " +  this.stop + "n");
CompletableFuture<Void> temp = services.thenAccept(x -> {
for (BusService service : x.keySet()) {
CompletableFuture<Set<BusStop>> stops = x.get(service);
result = result.thenApply(y -> y += describeService(service, stops));
}
});
return result;
}

public CompletableFuture<String> describeService(BusService service,
CompletableFuture<Set<BusStop>> stops) {
return stops.thenApply(x -> {
if (x.isEmpty()) {
return "";
}
return x.stream()
.filter(stop -> stop != this.stop)
.reduce("- Can take " + service + " to:n",
(str, stop) -> str += "  - " + stop + "n",
(str1, str2) -> str1 + str2);
});
}

我试图在description()的forloop中更新result,因为result.thenApply()导致了一个新的CompletableFuture实例,我需要将其重新分配给一个新变量来更新result,但我不太确定如何

您不需要将其重新分配给新变量,也不应该。相反,合并未来。

return services.thenCombine(result, (x, y) -> {
for (BusService service : x.keySet()) {
CompletableFuture<Set<BusStop>> stops = x.get(service);
y += describeService(service, stops);
}
return y;
});

最新更新