janput
12/5/2016 - 10:03 AM

Check for duplicates in a List

Check for duplicates in a List

    private void checkDuplicates(List<? extends Object> input){
        Map<Object, Long> countMap = new HashMap<>();
        for (Object o : input){
            if (countMap.containsKey(o)){
                countMap.put(o, countMap.get(o) + 1L);
            } else {
                countMap.put(o, 1L);
            }
        }

        StringBuilder sb = new StringBuilder();
        long i = 0L;
        for (Map.Entry<Object, Long> entry : countMap.entrySet()){
            if (entry.getValue() > 1L){
                sb.append(entry.getKey().getClass().getSimpleName()).append(entry.getKey()).append(": ").append(entry.getValue());
                i++;
            }
        }
        if (i > 0L) {
            LOGGER.info("Duplicates found: (" + i + " duplicates /" + input.size() + " items)\n" + sb.toString());
        } else {
            LOGGER.info("No duplicates found in " + input.size() + " items  :-)");
        }
    }