View Javadoc
1   package org.opentrafficsim.base.parameters.constraint;
2   
3   import java.util.Collection;
4   import java.util.LinkedHashSet;
5   
6   import org.djutils.exceptions.Throw;
7   
8   /**
9    * Constraint that checks whether a collection (the parameter value) is a subset of a constraint collection.
10   * <p>
11   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
12   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
13   * </p>
14   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
15   * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
16   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
17   * @param <T> object type
18   */
19  public class SubCollectionConstraint<T> implements Constraint<Collection<T>>
20  {
21  
22      /** Acceptable objects. */
23      @SuppressWarnings("checkstyle:visibilitymodifier")
24      protected final Collection<T> objects;
25  
26      /**
27       * @param objects acceptable objects
28       */
29      public SubCollectionConstraint(final Collection<T> objects)
30      {
31          Throw.whenNull(objects, "Collection of acceptable objects may not be null.");
32          this.objects = objects;
33      }
34  
35      @Override
36      public boolean accept(final Collection<T> value)
37      {
38          return this.objects.containsAll(value);
39      }
40  
41      @Override
42      public String failMessage()
43      {
44          return "Value of parameter '%s' contains value(s) not in the collection of acceptable values.";
45      }
46  
47      /**
48       * Creates a new instance with given collection.
49       * @param objs acceptable objects
50       * @param <T> type
51       * @return new instance with given collection
52       */
53      @SafeVarargs
54      public static <T> SubCollectionConstraint<T> newInstance(final T... objs)
55      {
56          Collection<T> collection = new LinkedHashSet<>();
57          for (T t : objs)
58          {
59              collection.add(t);
60          }
61          return new SubCollectionConstraint<>(collection);
62      }
63  
64      @Override
65      public String toString()
66      {
67          return "SubCollectionConstraint [objects=" + this.objects + "]";
68      }
69  
70  }