问题
I have an async method with a completeablefuture result:
public CompletableFuture<DogLater> asyncDogLater(String dogName){}
I have a list of dogs:
List<Dog> dogs;
Now, I want to create a map from the dog's name to the Completeablefuture:
Map<String, CompletableFuture<DogLater>> map;
After checking this and this I was trying to do so:
Map<String, CompletableFuture<DogLater>> completableFutures = dogs.stream()
.collect( Collectors.toMap(Dog::getName,
asyncDogLater(Dog::getName )));
But the compiler complains that the first Dog::getName
is problematic since:
Non-static method cannot be referenced from a static context
And the second Dog::getName
has an error of:
String is not a functional interface
I also checked this post, but I'm still not sure how to solve this.
回答1:
Collectors.toMap()
s second argument needs to be of type Function<T,R>
, in your case Function<Dog,CompletableFuture<DogLater>>
.
asyncDogLater(Dog::getName)
is of type Function<Function<Dog, String>, CompletableFuture<DogLater>>
if I'm not mistaken.
You need toMap(Dog::getName, d -> asyncDogLater(d.getName()))
.
来源:https://stackoverflow.com/questions/56462721/how-to-turn-a-listitem-to-a-mapitem-completeablefuturexyz