怎么打印出数组中的重复元素?

阅读量: 521 编辑

怎样打印出数组中的重复元素?

方法一

public void duplicateM1(String[] names) {
    for (int i = 0; i < names.length; i++) {
        for (int j = i + 1; j < names.length; j++) {
            if (names[i].equals(names[j])) { 
				// got the duplicate element
            }
        }
    }
}

方法二

public void duplicateM2(String[] names) {
    Set<String> set = new HashSet<String>();
    for (String name : names) {
        if (set.add(name) == false) {
            // got the duplicate element
        }
    }
}

方法三

public void duplicateM3(String[] names) {
    Map<String, Integer> nameAndCount = new HashMap<>();

    for (String name : names) {
        Integer count = nameAndCount.get(name);
        if (count == null) {
            nameAndCount.put(name, 1);
        } else {
            nameAndCount.put(name, ++count);
        }
    }

    Set<Map.Entry<String, Integer>> entrySet = nameAndCount.entrySet();
    for (Map.Entry<String, Integer> entry : entrySet) {
        if (entry.getValue() > 1) {
            System.out.printf("duplicate element '%s' and count '%d' :", entry.getKey(), entry.getValue());
        }
    }

}

苏ICP备13052010号-3
©2022 南京匠成信息科技有限公司