代码之家  ›  专栏  ›  技术社区  ›  riorio

如何将列表<item>转换为地图<item,completablefuture<xyz>>

  •  1
  • riorio  · 技术社区  · 7 年前

    我有一个异步方法,它有一个完整的未来结果:

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

    我有一张狗的名单:

    List<Dog> dogs;
    

    现在,我想创建一张从狗的名字到完整未来的地图:

    Map<String, CompletableFuture<DogLater>> map;
    

    检查后 this 和 this 我试着这么做:

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

    但是编译器抱怨第一个 Dog::getName 问题在于:

    无法从静态上下文引用非静态方法

    第二个呢 狗:getName 有一个错误:

    字符串不是函数接口

    我也查过了 this post ,但我仍然不知道如何解决这个问题。

    0 回复  |  直到 7 年前
        1
  •  2
  •   daniu    7 年前

    Collectors.toMap() 的第二个参数必须是 Function<T,R> 对你来说 Function<Dog,CompletableFuture<DogLater>> .

    asyncDogLater(Dog::getName) 是一种 Function<Function<Dog, String>, CompletableFuture<DogLater>> 如果我没弄错的话。

    你需要 toMap(Dog::getName, d -> asyncDogLater(d.getName())) .

    推荐文章