0
点赞
收藏
分享

微信扫一扫

java 查找数组中重复元素,并计算每个元素出现多少次

霍华德 2022-02-08 阅读 147

查找数组中重复元素,并计算每个元素出现多少次

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}
举报

相关推荐

0 条评论