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

cdc.applic.dictionaries.edit.checks.utils.AmbiguityHelper 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.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

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

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

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

    public static  AmbiguityHelper 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 AmbiguityHelper<>(keysExtractor,
                                     keyValidator);
    }

    public List getAmbiguities(List elements,
                                  List with) {
        final List list = elements.stream()
                                     .flatMap(e -> keysExtractor.apply(e).stream())
                                     .filter(keyValidator)
                                     .toList();
        final Set set = with.stream()
                               .flatMap(e -> keysExtractor.apply(e).stream())
                               .filter(keyValidator)
                               .collect(Collectors.toSet());

        final List ambiguities = new ArrayList<>();
        for (final K k : list) {
            if (set.contains(k)) {
                ambiguities.add(k);
            }
        }

        return ambiguities;
    }

    public boolean hasAmbiguities(List elements,
                                  List with) {
        return !getAmbiguities(elements, with).isEmpty();
    }

    public String explain(List elements,
                          List with) {
        final List ambiguities = getAmbiguities(elements, with);

        return ambiguities.stream()
                          .map(Object::toString)
                          .collect(Collectors.joining(", "));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy