如何使用第二个 ComputableFuture 对象设置 CompletableFuture 对象的字段值

How to set field value of CompletableFuture object with second ComputableFuture object

我有一个方法:

public CompletableFuture<List<Employee>> handleFutures(CompletableFuture<Factory> factoryCompletableFuture, CompletableFuture<Task> taskCompletableFuture)
      throws ExecutionException, InterruptedException {
      //logic
}

我想用CompletableFuture<Task> taskCompletableFuture设置CompletableFuture<Factory> factoryCompletableFuture对象中字段task的值。

任务 class 看起来像:

public enum Task {
    MECHANIC,
    ENGINEER
}

员工 class 看起来像:

public class Employee {
    private Task task;
}

工厂 class 看起来像:

public class Factory{
    private Optional<List<Employee>> employees;
}

我有这样的流:

    Task task = taskCompletableFuture.get();

    List<Employee> collect = factoryCompletableFuture.get().getEmployees().stream()
        .flatMap(Collection::stream)
        .peek(empl -> empl.setTask(task))
        .map(CompletableFuture::completedFuture)
        .map(CompletableFuture::join)
        .collect(toList());

哪个 return 员工列表。

我想要实现的是用 CompletableFuture 以一种温和的方式在流上方包装以获得结果 CompletableFuture<List<Employee>> 并调用方法逻辑,如:

return factoryCompletableFuture.thenApply(do logic here which will set value and return CompletableFuture). 

顺便说一句,我知道带有列表的 Optional 不是一个好的做法,但我无法更改它。 Peek for setter 用法不是最佳选择,但此操作不需要额外的对象来重新打包已更改的对象,最终使用 forEach。

如果能就如何实现理想目标提出建议,我将不胜感激。

您只需要使用 thenCombine():

public CompletableFuture<List<Employee>> handleFutures(
        CompletableFuture<Factory> factoryCompletableFuture,
        CompletableFuture<Task> taskCompletableFuture) {
    return factoryCompletableFuture.thenCombine(taskCompletableFuture,
        (factory, task) -> factory.getEmployees().stream()
            .flatMap(Collection::stream)
            .peek(empl -> empl.setTask(task))
            .collect(toList()));
}