【问题标题】:How to turn a List<Item> to a Map<Item, completeablefuture<xyz>>如何将 List<Item> 转换为 Map<Item, completablefuture<xyz>>
【发布时间】:2019-06-05 14:37:22
【问题描述】:

我有一个具有可完成未来结果的异步方法:

public CompletableFuture<DogLater> asyncDogLater(String dogName){}

我有一份狗的名单:

List<Dog> dogs;

现在,我想创建一张从狗的名字到 Completeablefuture 的地图:

Map<String, CompletableFuture<DogLater>> map;

在检查了thisthis 之后,我试图这样做:

    Map<String, CompletableFuture<DogLater>> completableFutures = dogs.stream()
            .collect( Collectors.toMap(Dog::getName,
                                       asyncDogLater(Dog::getName )));

但编译器抱怨第一个Dog::getName 有问题,因为:

不能从静态上下文中引用非静态方法

而第二个Dog::getName有一个错误:

字符串不是函数式接口

我也检查了this post,但我仍然不确定如何解决这个问题。

【问题讨论】:

  • 你需要toMap(Dog::getName, d -&gt; asyncDogLater(d.getName()))
  • @daniu 完美运行。您想将其添加为荣誉的答案吗?

标签: java java-stream completable-future method-reference


【解决方案1】:

Collectors.toMap()s 第二个参数必须是Function&lt;T,R&gt; 类型,在你的情况下为Function&lt;Dog,CompletableFuture&lt;DogLater&gt;&gt;

如果我没记错的话,asyncDogLater(Dog::getName) 的类型是 Function&lt;Function&lt;Dog, String&gt;, CompletableFuture&lt;DogLater&gt;&gt;

你需要toMap(Dog::getName, d -&gt; asyncDogLater(d.getName()))

【讨论】:

    猜你喜欢
    • 2020-12-18
    • 2021-02-11
    • 2017-03-29
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2021-03-16
    • 2017-07-14
    相关资源
    最近更新 更多