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.io.Serializable;
21 import java.util.HashSet;
22 import java.util.Set;
23
24 /***
25 * <code>Predicate</code> implementation that returns <code>true</code> the
26 * first time any given object is evaluated by the <code>Predicate</code>, and
27 * returns <code>false</code> every time the same object is subsequently
28 * evaluated</code>.
29 *
30 * @author Stephen Colebourne
31 * @author Chris Lambrou (port to Java 5.0)
32 * @since Collections15 1.0
33 */
34 public final class UniquePredicate <E> implements Predicate<E>, Serializable
35 {
36
37 static final long serialVersionUID = 5170814862386683025L;
38
39 /***
40 * The set of previously evaluated objects.
41 */
42 private final Set<E> evaluatedObjects = new HashSet<E>();
43
44 /***
45 * Creates and returns a new <code>UniquePredicate</code> instance.
46 *
47 * @return A new <code>UniquePredicate</code> instance.
48 */
49 public static <T> Predicate<T> getInstance()
50 {
51 return new UniquePredicate<T>();
52 }
53
54 /***
55 * Creates a new <code>UniquePredicate</code> instance.
56 */
57 protected UniquePredicate()
58 {
59 }
60
61 /***
62 * Evaluates the <code>Predicate</code> returning <code>true</code> only if
63 * the input object hasn't been previously evaluated by this
64 * <code>Predicate</code>.
65 *
66 * @param object The input object to evaluate.
67 *
68 * @return <code>true</code> if this is the first time the object has been
69 * evaluated by this <code>Predicate</code>. <code>false</code> if
70 * the opject has ben previously evaluated by this
71 * <code>Predicate</code>.
72 */
73 public boolean evaluate(E object)
74 {
75 return evaluatedObjects.add(object);
76 }
77
78 }