Bud*_*dhi 4 java java-8 java-stream
我想将int数组转换为
Map<Integer,Integer>
Run Code Online (Sandbox Code Playgroud)
使用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));
Run Code Online (Sandbox Code Playgroud)
我想得到一个如下图,键将是整数值,值将是每个键的总计数
map = {2-> 3,7-> 1,11-> 2,15-> 1}
编译器抱怨“ 不存在类型变量T,U的实例,因此Integer向Function确认 ”
感谢任何指针来解决这个问题
您需要将装箱IntStream,然后使用groupingByvalue获得计数:
Map<Integer, Long> map = Arrays
.stream(nums)
.boxed() // this
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)
或reduce用作:
Map<Integer, Integer> map = Arrays
.stream(nums)
.boxed()
.collect(Collectors.groupingBy(e -> e,
Collectors.reducing(0, e -> 1, Integer::sum)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
331 次 |
| 最近记录: |