1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.collections15.functors.predicate;
17
18 import net.sf.collections15.Predicate;
19
20 import java.util.Collection;
21
22 /***
23 * <code>Predicate</code> implementation that returns <code>true</code> if
24 * exactly one decorated <code>Predicate</code>s return <code>true</code>.
25 *
26 * @author Stephen Colebourne
27 * @author Chris Lambrou (port to Java 5.0)
28 * @since Collections15 1.0
29 */
30 public final class OnePredicate <E> extends AbstractMultplePredicateDecorator<E>
31 {
32
33 static final long serialVersionUID = 6474539966282189151L;
34
35 /***
36 * Returns an instance that wraps the specified collection of
37 * <code>Predicate</code>s.
38 *
39 * @param predicates The <cod>Predicate</code>s to wrap. The contents of the
40 * collection are defensively copied by the new instance.
41 *
42 * @return A <code>Predicate</code> instance that will only evaluate to
43 * <code>true</code> if exactly one of the wrapped
44 * <code>Predicate</code>s evaluates to <code>true</code>.
45 *
46 * @throws IllegalArgumentException Thrown if the collection, or any of its
47 * elements are <code>null</code>. The
48 * collection may be empty, however, in
49 * which case the resulting <code>AnyPredicate</code>
50 * will always return <code>false</code>.
51 */
52 public static <T> OnePredicate<T> getInstance(Collection<Predicate<? super T>> predicates)
53 {
54 return new OnePredicate<T>(predicates);
55 }
56
57 /***
58 * Creates a new instance that wraps the specified collection of
59 * <code>Predicate</code>s.
60 *
61 * @param predicates The <cod>Predicate</code>s to wrap. The contents of the
62 * collection are defensively copied by the new instance.
63 *
64 * @throws IllegalArgumentException Thrown if the collection, or any of its
65 * elements are <code>null</code>. The
66 * collection may be empty, however, in
67 * which case the resulting <code>AnyPredicate</code>
68 * will always return <code>false</code>.
69 */
70 protected OnePredicate(Collection<Predicate<? super E>> predicates)
71 {
72 super(predicates);
73 }
74
75 /***
76 * Evaluates the <code>Predicate</code> returning <code>true</code> exactly
77 * one of the decorated <code>Predicate</code>s returns <code>true</code>.
78 *
79 * @param object The input object to evaluate.
80 *
81 * @return <code>true</code> if exactly one of the decorated
82 * <code>Predicate</code>s returns <code>true</code>.
83 */
84 public boolean evaluate(E object)
85 {
86 boolean match = false;
87 int size = decoratedPredicates.size();
88 for (int i = 0; i < size; i++) {
89 if (decoratedPredicates.get(i).evaluate(object)) {
90 if (match) {
91 return false;
92 }
93 match = true;
94 }
95 }
96 return match;
97 }
98
99 }