简体   繁体   English

如何获得期货清单的结果

[英]How to get result of list of futures

I have List of futures 我有期货清单

List<Future<Boolean>> futures = service.invokeAll( Arrays.asList( callable1, callable2 ));

what i need is a way to get a list of results 我需要的是一种获取结果列表的方法

can you provide a solution in java? 可以提供Java解决方案吗?

something like whenAll()... 类似于whenAll()...

What you are after is the allMatch() method like this: 您所需要的是allMatch()方法,如下所示:

boolean result = futures.stream().allMatch(booleanFuture -> {
    try
    {
        return booleanFuture.get();
    }
    catch (InterruptedException | ExecutionException e)
    {
        throw new RuntimeException(e);
    }
});

If you really meant a list of results, then it is map() you are after like this: 如果您真的想要一个结果列表,那么您将使用map() ,如下所示:

List<Boolean> results = futures.stream().map(booleanFuture -> {
    try
    {
        return booleanFuture.get();
    }
    catch (InterruptedException | ExecutionException e)
    {
        throw new RuntimeException(e);
    }
}).collect(Collectors.toList());

Modifiying @Vampire 's results You can also use a parallelStream like one shown below if it is a lot of data 修改@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM