Skip to content

Validation for "allOf" #436

Closed
Closed
@ShivKJ

Description

@ShivKJ

I am trying to find a validation when a list contains all items present in another list.

I see methods such notOneOf (perhaps it can be renamed noneOf), oneOf but something like allOf is missing. I tried adding it like below,

import static com.google.common.collect.Sets.difference;
import static java.util.stream.Collectors.joining;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import am.ik.yavi.core.CustomConstraint;

public final class ContainsAllOf<T> implements CustomConstraint<List<T>> {
    private final Set<T> values;

    public ContainsAllOf(Collection<? extends T> values) {
        this.values = Set.copyOf(values);
    }

    @Override
    public boolean test(List<T> ts) {
        return new HashSet<>(ts).containsAll(values);
    }

    @Override
    public Object[] arguments(List<T> violatedValue) {
        var missingValues = difference(values, new HashSet<>(violatedValue)).stream()
                .map(Objects::toString)
                .collect(joining(", "));

        return new Object[]{missingValues};
    }

    @Override
    public String defaultMessageFormat() {
        return "{0} -> {1}";
    }

    @Override
    public String messageKey() {
        return "<should contain all of(" + values + ")>";
    }
}

Can we have it in the lib itself?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions