[英]How to get result of list of futures
我有期貨清單
List<Future<Boolean>> futures = service.invokeAll( Arrays.asList( callable1, callable2 ));
我需要的是一種獲取結果列表的方法
可以提供Java解決方案嗎?
類似於whenAll()...
您所需要的是allMatch()
方法,如下所示:
boolean result = futures.stream().allMatch(booleanFuture -> {
try
{
return booleanFuture.get();
}
catch (InterruptedException | ExecutionException e)
{
throw new RuntimeException(e);
}
});
如果您真的想要一個結果列表,那么您將使用map()
,如下所示:
List<Boolean> results = futures.stream().map(booleanFuture -> {
try
{
return booleanFuture.get();
}
catch (InterruptedException | ExecutionException e)
{
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
修改@Vampire的結果如果數據很多,也可以使用如下所示的parallelStream。
List<Boolean> results = futures.parallelStream().map(booleanFuture -> {
try
{
return booleanFuture.get();
}
catch (InterruptedException | ExecutionException e)
{
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.