All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cdc.applic.dictionaries.edit.checks.utils.DuplicateHelper Maven / Gradle / Ivy

There is a newer version: 0.13.3
Show newest version
package cdc.applic.dictionaries.edit.checks.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public final class DuplicateHelper {
    private final Function> keysExtractor;
    private final Predicate keyValidator;

    private DuplicateHelper(Function> keysExtractor,
                            Predicate keyValidator) {
        this.keysExtractor = keysExtractor;
        this.keyValidator = keyValidator;
    }

    public static  DuplicateHelper ofN(Function> keysExtractor,
                                                   Predicate keyValidator) {
        return new DuplicateHelper<>(keysExtractor,
                                     keyValidator);
    }

    public static  DuplicateHelper of1(Function keyExtractor,
                                                   Predicate keyValidator) {
        final Function> keysExtractor =
                e -> {
                    final K k = keyExtractor.apply(e);
                    return keyValidator.test(k) ? Set.of(k) : Set.of();
                };
        return new DuplicateHelper<>(keysExtractor,
                                     keyValidator);
    }

    public boolean hasDuplicates(List elements) {
        final List list = elements.stream()
                                     .flatMap(e -> keysExtractor.apply(e).stream())
                                     .filter(keyValidator)
                                     .toList();
        final Set set = new HashSet<>(list);
        return list.size() != set.size();
    }

    private Map> counts(List elements) {
        final Map> map = new HashMap<>();
        for (final E element : elements) {
            final Set keys = keysExtractor.apply(element);
            for (final K key : keys) {
                if (keyValidator.test(key)) {
                    final List list = map.computeIfAbsent(key, k -> new ArrayList<>());
                    list.add(element);
                }
            }
        }
        return map;
    }

    public String explain(List elements) {
        final Map> counts = counts(elements);
        return counts.entrySet()
                     .stream()
                     .filter(e -> e.getValue().size() > 1)
                     .map(e -> e.getKey() + " (x" + e.getValue().size() + ")")
                     .sorted()
                     .collect(Collectors.joining(", "));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy