1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.collections.functors;
  17. import java.io.Serializable;
  18. import java.util.HashSet;
  19. import java.util.Set;
  20. import org.apache.commons.collections.Predicate;
  21. /**
  22. * Predicate implementation that returns true the first time an object is
  23. * passed into the predicate.
  24. *
  25. * @since Commons Collections 3.0
  26. * @version $Revision: 1.4 $ $Date: 2004/05/16 11:16:01 $
  27. *
  28. * @author Stephen Colebourne
  29. */
  30. public final class UniquePredicate implements Predicate, Serializable {
  31. /** Serial version UID */
  32. static final long serialVersionUID = -3319417438027438040L;
  33. /** The set of previously seen objects */
  34. private final Set iSet = new HashSet();
  35. /**
  36. * Factory to create the predicate.
  37. *
  38. * @return the predicate
  39. * @throws IllegalArgumentException if the predicate is null
  40. */
  41. public static Predicate getInstance() {
  42. return new UniquePredicate();
  43. }
  44. /**
  45. * Constructor that performs no validation.
  46. * Use <code>getInstance</code> if you want that.
  47. */
  48. public UniquePredicate() {
  49. super();
  50. }
  51. /**
  52. * Evaluates the predicate returning true if the input object hasn't been
  53. * received yet.
  54. *
  55. * @param object the input object
  56. * @return true if this is the first time the object is seen
  57. */
  58. public boolean evaluate(Object object) {
  59. return iSet.add(object);
  60. }
  61. }