我想将int 数组转换为Map<Integer,Integer>使用 Java 8 流 APIint[] nums={2, 7, 11, 15, 2, 11, 2};
Map<Integer,Integer> map=Arrays
.stream(nums)
.collect(Collectors.toMap(e->e,1));我想得到如下图,键是整数值,值是每个键的总数地图={2->3, 7->1, 11->2, 15->1}编译器抱怨“不存在类型变量 T、U 的实例,因此 Integer 确认为 Function ”感谢任何解决此问题的建议
3 回答

慕少森
TA贡献2019条经验 获得超9个赞
您需要装箱IntStream
然后使用groupingBy
值来获取计数:
Map<Integer, Long> map = Arrays .stream(nums) .boxed() // this .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
或reduce
用作:
Map<Integer, Integer> map = Arrays .stream(nums) .boxed() .collect(Collectors.groupingBy(e -> e, Collectors.reducing(0, e -> 1, Integer::sum)));

qq_遁去的一_1
TA贡献1725条经验 获得超8个赞
您必须调用.boxed()
您的 Stream 将 转换IntStream
为Stream<Integer>
. 然后你可以使用Collectors.groupingby()
和Collectors.summingInt()
来计算值:
Map<Integer, Integer> map = Arrays.stream(nums).boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(i -> 1)));

GCT1015
TA贡献1827条经验 获得超4个赞
您还可以在不将int值装箱到Map<Integer, Integer>or中的情况下完成对 int 的计数Map<Integer, Long>。如果您使用Eclipse Collections,您可以将 an 转换IntStream为 an IntBag,如下所示。
int[] nums = {2, 7, 11, 15, 2, 11, 2};
IntBag bag = IntBags.mutable.withAll(IntStream.of(nums));
System.out.println(bag.toStringOfItemToCount());
输出:
{2=3, 7=1, 11=2, 15=1}
您也可以IntBag直接从int数组构造。
IntBag bag = IntBags.mutable.with(nums);
注意:我是 Eclipse Collections 的提交者。
添加回答
举报
0/150
提交
取消