cdc.applic.dictionaries.edit.checks.utils.DuplicateHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cdc-applic-dictionaries-edit Show documentation
Show all versions of cdc-applic-dictionaries-edit Show documentation
Applicabilities Dictionaries Edition.
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 extends E> 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 extends E> 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 extends E> 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(", "));
}
}