Reputation: 1269
I am trying to collect a List of Collections into a Map, where the key is the index from the original list and the value is the collection. I tried the following, but I get a Type mismatch error: Type mismatch: cannot convert from Map<Object,Object> to Map<Integer,Collection<String>>
My code:
public Map<Integer, Collection<String>> myFunction(final List<Collection<String>> strs) {
return strs.stream().collect(Collectors.toMap(List::indexOf, v -> v)); // Error here
}
Any suggestions?
Upvotes: 2
Views: 2215
Reputation: 230
you can do like this:
List<Collection<Integer>> list = ...;
Map<Integer, Collection<Integer>> collect = IntStream.range(0, list.size())
.boxed()
.collect(Collectors.toMap(Function.identity(), v -> list.get(v)));
Upvotes: 1
Reputation: 45339
You have a compilation error: Cannot make a static reference to the non-static method indexOf(Object) from the type List
.
If you correct it as below, it will compile:
return strs.stream().collect(Collectors.toMap(coll -> strs.indexOf(coll), v -> v));
Or, using a method reference:
return strs.stream().collect(Collectors.toMap(strs::indexOf, v -> v));
Upvotes: 1