代码:
public class Test {
public static void main(String[] args) {
// 测试数据
int[] a = {1,5,4,5,3,1,2,6};
// 键存储数字,值存储数字出现的次数
Map<Integer,Integer> map = new HashMap<>();
// 遍历数组
for (int i = 0;i<a.length;i++){
// 判断集合里面是否已经存储了该数字
if (map.containsKey(a[i])){
// 如果集合中已经存储了该数字,那就让数目加1
map.put(a[i],map.get(a[i])+1);
}else{
// 如果集合中没有存储该数字,那就初始化数目为1
map.put(a[i],1);
}
}
// 遍历集合中的数据
Set<Integer> set = map.keySet();
for (Integer key : set){
System.out.println(key+":"+map.get(key));
}
}
}
结果:
1:2
2:1
3:1
4:1
5:2
6:1