001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.collections4.functors;
018
019import java.io.Serializable;
020import java.util.HashSet;
021import java.util.Set;
022
023import org.apache.commons.collections4.Predicate;
024
025/**
026 * Predicate implementation that returns true the first time an object is
027 * passed into the predicate.
028 *
029 * @since 3.0
030 * @version $Id: UniquePredicate.html 972421 2015-11-14 20:00:04Z tn $
031 */
032public final class UniquePredicate<T> implements Predicate<T>, Serializable {
033
034    /** Serial version UID */
035    private static final long serialVersionUID = -3319417438027438040L;
036
037    /** The set of previously seen objects */
038    private final Set<T> iSet = new HashSet<T>();
039
040    /**
041     * Factory to create the predicate.
042     *
043     * @param <T> the type that the predicate queries
044     * @return the predicate
045     * @throws IllegalArgumentException if the predicate is null
046     */
047    public static <T> Predicate<T> uniquePredicate() {
048        return new UniquePredicate<T>();
049    }
050
051    /**
052     * Constructor that performs no validation.
053     * Use <code>uniquePredicate</code> if you want that.
054     */
055    public UniquePredicate() {
056        super();
057    }
058
059    /**
060     * Evaluates the predicate returning true if the input object hasn't been
061     * received yet.
062     *
063     * @param object  the input object
064     * @return true if this is the first time the object is seen
065     */
066    public boolean evaluate(final T object) {
067        return iSet.add(object);
068    }
069
070}