我想將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
提交
取消