    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 */
    031public final class UniquePredicate<T> implements Predicate<T>, Serializable {
    032
    033    /** Serial version UID */
    034    private static final long serialVersionUID = -3319417438027438040L;
    035
    036    /**
    037     * Factory to create the predicate.
    038     *
    039     * @param <T> the type that the predicate queries
    040     * @return the predicate
    041     * @throws IllegalArgumentException if the predicate is null
    042     */
    043    public static <T> Predicate<T> uniquePredicate() {
    044        return new UniquePredicate<>();
    045    }
    046
    047    /** The set of previously seen objects */
    048    private final Set<T> iSet = new HashSet<>();
    049
    050    /**
    051     * Constructor that performs no validation.
    052     * Use {@code uniquePredicate} if you want that.
    053     */
    054    public UniquePredicate() {
    055    }
    056
    057    /**
    058     * Evaluates the predicate returning true if the input object hasn't been
    059     * received yet.
    060     *
    061     * @param object  the input object
    062     * @return true if this is the first time the object is seen
    063     */
    064    @Override
    065    public boolean evaluate(final T object) {
    066        return iSet.add(object);
    067    }
    068
    069}