当需要 Completable<Void> 时返回 Completable<Object>

我有以下人员类别:


class Person {

    String name;

    String city;

    public void setInfo(PersonInformation info) {//...};

}

我有一个来自此类的对象列表,我想使用返回 CompletableFuture 的方法异步查询列表中每个项目的数据库来填充它们的信息:


List<CompletableFuture<Void>> populateInformation(List<Person> people) {

     return people.stream().

            .collect(groupingBy(p -> p.getLocation(), toList()))

            .entrySet().stream()

            .map(entry -> 

                    CompletableFuture.supplyAsync(

                            () -> db.getPeopleInformation(entry.getKey())

                    ).thenApply(infoList -> { 

                                    //do something with info list that doens't return anything

                                    // apparently we HAVE to return null, as callanbles have to return a value

                                    return null;

                                }

                    )

            ).collect(Collectors.toList());

}

问题是我收到编译错误,因为方法中的代码返回CompletableFuture<List<Object>>而不是CompletableFuture<List<Void>>. 我在这里做错了什么?


我想过删除return null,但正如我在评论中提到的,似乎在可调用中我们必须返回一个值,否则会出现另一个编译错误:Incompatible types: expected not void but the lambda body is a block that is not value-compatible


拉丁的传说
浏览 99回答 2
2回答

萧十郎

thenApply方法返回类型为CompletableFuture<U>,这意味着返回 CompletableFuture 并带有函数返回值public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)返回一个新CompletionStage值,当此阶段正常完成时,将使用此阶段的结果作为所提供函数的参数来执行该新值。有关异常完成的规则,请参阅 CompletionStage 文档。Type Parameters: U - the function's return type Parameters: fn - the function to use to compute the value of the returned CompletionStage使用thenAccept方法返回 Void 类型的 CompletableFuturepublic CompletableFuture<Void> thenAccept(Consumer<? super T> action)返回一个新的 CompletionStage,当该阶段正常完成时,将使用该阶段的结果作为所提供操作的参数来执行该阶段。有关异常完成的规则,请参阅 CompletionStage 文档。Parameters: action - the action to perform before completing the returned CompletionStage

摇曳的蔷薇

您也可以通过两种方式强制thenApply返回 a :CompletableFuture<Void>指定泛型类型参数:).<Void>thenApply(infoList -> {转换返回值:return (Void) null;当然,你可以两者都做,但那是多余的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java