如何将 List<Item> 转换为 Map<Item, completeablefuture<xyz>>
How to turn a List<Item> to a Map<Item, completeablefuture<xyz>>
我有一个带有未来可完成结果的异步方法:
public CompletableFuture<DogLater> asyncDogLater(String dogName){}
我有一份狗的清单:
List<Dog> dogs;
现在,我想创建一个从狗的名字到 Completeablefuture 的映射:
Map<String, CompletableFuture<DogLater>> map;
检查后 this and this 我正在尝试这样做:
Map<String, CompletableFuture<DogLater>> completableFutures = dogs.stream()
.collect( Collectors.toMap(Dog::getName,
asyncDogLater(Dog::getName )));
但是编译器抱怨第一个 Dog::getName
有问题,因为:
Non-static method cannot be referenced from a static context
而第二个 Dog::getName
有一个错误:
String is not a functional interface
我也检查了,但我仍然不确定如何解决这个问题。
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()))
.
我有一个带有未来可完成结果的异步方法:
public CompletableFuture<DogLater> asyncDogLater(String dogName){}
我有一份狗的清单:
List<Dog> dogs;
现在,我想创建一个从狗的名字到 Completeablefuture 的映射:
Map<String, CompletableFuture<DogLater>> map;
检查后 this and this 我正在尝试这样做:
Map<String, CompletableFuture<DogLater>> completableFutures = dogs.stream()
.collect( Collectors.toMap(Dog::getName,
asyncDogLater(Dog::getName )));
但是编译器抱怨第一个 Dog::getName
有问题,因为:
Non-static method cannot be referenced from a static context
而第二个 Dog::getName
有一个错误:
String is not a functional interface
我也检查了
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()))
.