我有一个整型数组:
{1,2,4,2,3,5,6,4,3}
我该如何找到数组元素的频率,例如
1=1,2=2,3=2,4=4..
。我需要一个类,可以将我的数组传递给它,并返回一个数组,其中包含数组元素的计数。例如: array{[0]=1,[1]=2,[2]=3,[3]=4..}
(对于上述示例数组)。我有一个整型数组:
{1,2,4,2,3,5,6,4,3}
1=1,2=2,3=2,4=4..
。我需要一个类,可以将我的数组传递给它,并返回一个数组,其中包含数组元素的计数。例如: array{[0]=1,[1]=2,[2]=3,[3]=4..}
(对于上述示例数组)。Map<Integer, Integer> map = new HashMap<>();
int arr[] = new int[]{2, 2, 3, 3, 4, 5, 6, 7, 9, 9, 0, 4, 2};
for (int i = 0; i < arr.length; i++) {
Integer count = map.getOrDefault(arr[i], 0);
map.put(arr[i], count + 1);
}
//Print the map to see the occurrence
map.forEach((key, value) -> {
System.out.println(key + " -> " + value);
});
Collections.frequency(Arrays.asList(...), X)
- obatakuArrays.asList(int[])
方法会把整个int[]
数组作为一个对象处理,并返回一个只包含该数组的单例列表List<int[]>
。如果想要得到每个元素的封装类型Integer[]
,可以直接使用可变参数或传递Integer[]
数组。具体实现可以参考这个链接:http://ideone.com/TwS3yJ - obataku