SubCollectionConstraint.java

  1. package org.opentrafficsim.base.parameters.constraint;

  2. import java.util.Collection;
  3. import java.util.LinkedHashSet;

  4. import org.djutils.exceptions.Throw;

  5. /**
  6.  * Constraint that checks whether a collection (the parameter value) is a subset of a constraint collection.
  7.  * <p>
  8.  * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
  9.  * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  10.  * </p>
  11.  * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
  12.  * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
  13.  * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
  14.  * @param <T> object type
  15.  */
  16. public class SubCollectionConstraint<T> implements Constraint<Collection<T>>
  17. {

  18.     /** Acceptable objects. */
  19.     @SuppressWarnings("checkstyle:visibilitymodifier")
  20.     protected final Collection<T> objects;

  21.     /**
  22.      * @param objects acceptable objects
  23.      */
  24.     public SubCollectionConstraint(final Collection<T> objects)
  25.     {
  26.         Throw.whenNull(objects, "Collection of acceptable objects may not be null.");
  27.         this.objects = objects;
  28.     }

  29.     @Override
  30.     public boolean accept(final Collection<T> value)
  31.     {
  32.         return this.objects.containsAll(value);
  33.     }

  34.     @Override
  35.     public String failMessage()
  36.     {
  37.         return "Value of parameter '%s' contains value(s) not in the collection of acceptable values.";
  38.     }

  39.     /**
  40.      * Creates a new instance with given collection.
  41.      * @param objs acceptable objects
  42.      * @param <T> type
  43.      * @return new instance with given collection
  44.      */
  45.     @SafeVarargs
  46.     public static <T> SubCollectionConstraint<T> newInstance(final T... objs)
  47.     {
  48.         Collection<T> collection = new LinkedHashSet<>();
  49.         for (T t : objs)
  50.         {
  51.             collection.add(t);
  52.         }
  53.         return new SubCollectionConstraint<>(collection);
  54.     }

  55.     @Override
  56.     public String toString()
  57.     {
  58.         return "SubCollectionConstraint [objects=" + this.objects + "]";
  59.     }

  60. }