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