java - 流收集 toMap - 类型不匹配

java - Stream collect toMap - Type mismatch

我正在尝试将一个集合列表收集到一个映射中,其中键是原始列表中的索引,值是集合。我尝试了以下操作,但出现类型不匹配错误:Type mismatch: cannot convert from Map<Object,Object> to Map<Integer,Collection<String>>

我的代码:

public Map<Integer, Collection<String>> myFunction(final List<Collection<String>> strs) {
    return strs.stream().collect(Collectors.toMap(List::indexOf, v -> v)); // Error here
}

有什么建议吗?

您有一个编译错误:Cannot make a static reference to the non-static method indexOf(Object) from the type List

如果你更正如下,它会编译:

return strs.stream().collect(Collectors.toMap(coll -> strs.indexOf(coll), v -> v));

或者,使用方法参考:

return strs.stream().collect(Collectors.toMap(strs::indexOf, v -> v));

你可以这样做:

List<Collection<Integer>> list = ...;
Map<Integer, Collection<Integer>> collect = IntStream.range(0, list.size())
        .boxed()
        .collect(Collectors.toMap(Function.identity(), v -> list.get(v)));