Array to Map: 找不到适合 Collectors.toMap 的方法

Array to Map: no suitable method found for Collectors.toMap

我想使用 Java 8 个流将数组转换为 Map:

String[] arr = {"two", "times", "two", "is", "four"};
Arrays.stream(arr).collect(Collectors.toMap(s -> s, 1, Integer::sum);

s -> s 部分被标记为错误

no instance(s) of type variable(s) T, U exists so that Integer conforms to Function

实际上 1 是错误。值1不能作为valueMapper,其类型应该是Function<? super T, ? extends U>

在您的示例中,值映射器应该是一个接受 StreamString)和 returns 和 Integer 元素的函数。 lambda 表达式 s -> 1 就可以了。

以下作品:

String[] arr = {"two", "times", "two", "is", "four"};
Map<String,Integer> map = Arrays.stream(arr).collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
System.out.println (map);

输出:

{times=1, four=1, is=1, two=2}