Construct a Map using object reference as key using Streams API and Collectors.toMap()

删除回忆录丶 提交于 2019-12-07 20:03:45

问题


I want to construct a Map<Item, List<String>>, i.e. using the Item reference as key, with some arbitrary List<String> as value. I've attempted the following, but it will show type inference error in IntelliJ (however, it will still compile);

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream().collect(Collectors.toMap(i->i, new ArrayList<>()));

I then created a workaround through a helper method in Item, get(), which just returns its own instance;

public Item get(){ return this; }

Then tried the same approach, using the get() method to access the reference:

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream().collect(Collectors.toMap(Item::get, new ArrayList<>()));

Now it will at least compile, but it feels wrong.

How would one actually go around solving this in a proper manner?

Edit: Question is now radically different from what was originally posted, reflected by the comments received.


回答1:


In your first attempt, it should be :

List<Item> items = getItems(...);
Map<Item, String> itemMap = items.stream()
                                 .collect(Collectors.toMap(i->i, 
                                                           i->"some string"));

You were missing a ) and the parameter name for the lambda expression of the value.

Changing the value of the Map to a List doesn't make much difference :

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream()
                                       .collect(Collectors.toMap(i->i, 
                                                                 i->new ArrayList<>()));



回答2:


The proper way of achieving it was to include a type argument like so;

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream().collect(Collectors.toMap(Function.<Item>identity(), v -> new ArrayList<>()));

Alternatively;

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream().collect(Collectors.toMap(v -> v, v -> new ArrayList<String>()));


来源:https://stackoverflow.com/questions/28737658/construct-a-map-using-object-reference-as-key-using-streams-api-and-collectors-t

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