我有一个异步方法,它有一个完整的未来结果:
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 问题在于:
Dog::getName
无法从静态上下文引用非静态方法
第二个呢 狗:getName 有一个错误:
狗:getName
字符串不是函数接口
我也查过了 this post ,但我仍然不知道如何解决这个问题。
Collectors.toMap() 的第二个参数必须是 Function<T,R> 对你来说 Function<Dog,CompletableFuture<DogLater>> .
Collectors.toMap()
Function<T,R>
Function<Dog,CompletableFuture<DogLater>>
asyncDogLater(Dog::getName) 是一种 Function<Function<Dog, String>, CompletableFuture<DogLater>> 如果我没弄错的话。
asyncDogLater(Dog::getName)
Function<Function<Dog, String>, CompletableFuture<DogLater>>
你需要 toMap(Dog::getName, d -> asyncDogLater(d.getName())) .
toMap(Dog::getName, d -> asyncDogLater(d.getName()))