habitats
habitats

Reputation: 2471

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

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.

Upvotes: 2

Views: 4450

Answers (2)

habitats
habitats

Reputation: 2471

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>()));

Upvotes: 0

Eran
Eran

Reputation: 394006

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<>()));

Upvotes: 3

Related Questions