查找数组中重复元素,并计算每个元素出现多少次
public static void main(String[] args) {
int[] my_array = {a, b, c, c, d, d, e, b, g, b,j,j};
cfsz2(my_array);
}
//查找数组里重复的元素,每个元素出现几次
public static void cfsz2(int[] a){
//循环数组,添加到map
//如果map中没有这个数(key),put(值,1)
//有的话加一
Map<Integer,Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<a.length; i++){
if(map.containsKey(a[i])){
int val = map.get(a[i]);
map.put(a[i],val+1);
}else{
map.put(a[i],1);
}
}
System.out.println(map);
}
{a=1, b=3, c=2, d=2, e=1, g=1,j=2}