代码如下:
public class Count {
public static void main(String[] args) {
int[] arr={1,2,1,2,4,3,2,6,4,7,5,8,6};
Map<Integer,Integer> hashMap=new HashMap<Integer, Integer>();
for(int i=0; i<arr.length;i++){
if(hashMap.containsKey(arr[i])){
Integer value = hashMap.get(arr[i]);
hashMap.put(arr[i],value+1);
}else{
hashMap.put(arr[i],1);
}
}
Set<Integer> keys = hashMap.keySet();
for (Integer key : keys) {
System.out.println("元素:"+key+"出现的次数:"+hashMap.get(key));
}
}
}
输出结果: