1

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?

something like whenAll()...

Vampire
  • 35,631
  • 4
  • 76
  • 102
user8215502
  • 201
  • 2
  • 8
  • 1
    No, we are here to help you, but you´ll need to deliver your attempt first. – creyD Jun 29 '17 at 11:12
  • https://stackoverflow.com/q/30025428/1553934 look at this question. I think what you're looking for is `CompletableFuture.allOf(...)` – esin88 Jun 29 '17 at 11:13

2 Answers2

5

What you are after is the allMatch() method like this:

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:

List<Boolean> results = futures.stream().map(booleanFuture -> {
    try
    {
        return booleanFuture.get();
    }
    catch (InterruptedException | ExecutionException e)
    {
        throw new RuntimeException(e);
    }
}).collect(Collectors.toList());
Vampire
  • 35,631
  • 4
  • 76
  • 102
0

Modifiying @Vampire 's results You can also use a parallelStream like one shown below if it is a lot of data

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