找到数组中重复的元素,并返回重复的次数Java

找到数组中重复的元素,并返回重复的次数-Java

    @Test
    public void test13() {
    
    
        Integer[] arr = {
    
    1, 4, 1, 5, 6, 4, 1, 7, 1, 6};
        Map<Integer, Integer> map = findDupicatedInArray(arr);
        System.out.println(map);
    }

    public static < T > Map<T, Integer> findDupicatedInArray(T[] arr) {
    
    
        int count = 0;
        Map<T, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
    
    
            for (int j = i + 1; j < arr.length; j++) {
    
    
                if (arr[i] == arr[j]) {
    
    
                    count++;
                }
            }
            if (count != 0 && !map.containsKey(arr[i])) {
    
    
                System.out.println("count:"+count);
                map.put(arr[i], count+1);
            }
            count = 0;
        }
        return map;
    }

这里count:3
count:1
count:1
{1=4, 4=2, 6=2}

猜你喜欢

转载自blog.csdn.net/E_chos/article/details/114641656
今日推荐