我想要将 整型数组 转换为
Map<Integer,Integer>
使用Java 8流式API
int[] nums={2, 7, 11, 15, 2, 11, 2};
Map<Integer,Integer> map=Arrays
.stream(nums)
.collect(Collectors.toMap(e->e,1));
我想要得到一个像下面这样的地图,键将是整数值,值将是每个键的总计数
编译器报错 "不存在类型变量T,U的实例,因此Integer不能确认为Function的实例"map={2->3, 7->1, 11->2, 15->1}
感谢任何指针来解决这个问题。
Arrays.stream(nums).boxed().collect(Collectors.toMap(Function.identity(), i -> 1, Integer::sum));
的翻译如下:将nums
数组转换为流(stream),再对每个元素进行装箱(boxed)处理,最后使用Collectors.toMap(Function.identity(), i -> 1, Integer::sum)
方法将其收集为一个映射表(map)。其中,Function.identity()
表示使用元素本身作为键,i -> 1
表示将值初始化为 1,Integer::sum
表示合并时将值相加。 - Hadi J