要映射的Java 8 int数组
我想将int数组转换为要映射的Java 8 int数组,java,java-8,java-stream,Java,Java 8,Java Stream,我想将int数组转换为 Map<Integer,Integer> Map 使用Java8流api int[] nums={2, 7, 11, 15, 2, 11, 2}; Map<Integer,Integer> map=Arrays .stream(nums) .collect(Collectors.toMap(e->e,1)); int[]nums={2,7,11,15,2,11,2}; M
Map<Integer,Integer>
Map
使用Java8流api
int[] nums={2, 7, 11, 15, 2, 11, 2};
Map<Integer,Integer> map=Arrays
.stream(nums)
.collect(Collectors.toMap(e->e,1));
int[]nums={2,7,11,15,2,11,2};
Map=数组
.stream(nums)
.collect(Collectors.toMap(e->e,1));
我想得到一个像下面这样的映射,键将是整数值,值将是每个键的总计数
地图={2->3,7->1,11->2,15->1}
编译器抱怨“不存在类型变量T,U的实例,因此Integer确认为函数”
感谢任何解决此问题的指针您需要将
IntStream
框起来,然后使用groupingBy
值获取计数:
Map<Integer, Long> map = Arrays
.stream(nums)
.boxed() // this
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
必须在流上调用
.boxed()
,才能将IntStream
转换为流。然后,您可以使用Collectors.groupingby()
和Collectors.summingit()
来计算值:
Map<Integer, Integer> map = Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(i -> 1)));
Map Map=Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(Function.identity(),Collectors.summingit(i->1));
您也可以在不将int
值装箱到Map
或Map
的情况下完成int的计数。如果使用,可以将IntStream
转换为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}
您还可以直接从int
数组构造IntBag
IntBag bag = IntBags.mutable.with(nums);
注意:我是Eclipse集合的提交者。Arrays.stream(nums).boxed().collect(Collectors.toMap(Function.identity(),I->1,Integer::sum))代码>谢谢你的回答,如果map值只是1而不是key count,那么可以通过修改it@Buddhi,不,应该是…Collectors.toMap(e->e,v->1).
@HadiJ但在这种特定情况下,您需要Collectors.toMap(e->e,v->1,Integer::sum)
来处理重复项。@Holger,是的,我是指这个…映射(e->e,1)
。谢谢你的澄清
IntBag bag = IntBags.mutable.with(nums);