【问题标题】:Array to Map: no suitable method found for Collectors.toMap [closed]数组到地图:没有找到适合 Collectors.toMap 的方法 [关闭]
【发布时间】:2020-05-29 02:56:30
【问题描述】:

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

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

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

不存在类型变量 T, U 的实例,因此 Integer 符合 Function

【问题讨论】:

  • toMap 的第二个参数是一个函数,所以将1 更改为u -> 1

标签: java dictionary java-stream collect


【解决方案1】:

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

在您的示例中,值映射器应该是一个接受StreamString)元素并返回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}

【讨论】:

  • 不知道为什么这被否决了,因为它是正确的。虽然Collectors.counting() 可能是更好的选择
猜你喜欢
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 2014-08-27
  • 2021-06-19
  • 2015-11-26
相关资源
最近更新 更多