How to turn a List<Item> to a Map<Item, completeablefuture<xyz>>

[亡魂溺海] 提交于 2019-12-22 18:52:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!