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;
020
021import org.apache.commons.collections4.Predicate;
022import org.apache.commons.collections4.Transformer;
023
024/**
025 * Transformer implementation that calls a Predicate using the input object
026 * and then returns the result.
027 *
028 * @since 3.0
029 */
030public class PredicateTransformer<T> implements Transformer<T, Boolean>, Serializable {
031
032    /** Serial version UID */
033    private static final long serialVersionUID = 5278818408044349346L;
034
035    /**
036     * Factory method that performs validation.
037     *
038     * @param <T>  the input type
039     * @param predicate  the predicate to call, not null
040     * @return the {@code predicate} transformer
041     * @throws IllegalArgumentException if the predicate is null
042     */
043    public static <T> Transformer<T, Boolean> predicateTransformer(final Predicate<? super T> predicate) {
044        if (predicate == null) {
045            throw new IllegalArgumentException("Predicate must not be null");
046        }
047        return new PredicateTransformer<>(predicate);
048    }
049
050    /** The closure to wrap */
051    private final Predicate<? super T> iPredicate;
052
053    /**
054     * Constructor that performs no validation.
055     * Use {@code predicateTransformer} if you want that.
056     *
057     * @param predicate  the predicate to call, not null
058     */
059    public PredicateTransformer(final Predicate<? super T> predicate) {
060        iPredicate = predicate;
061    }
062
063    /**
064     * Gets the predicate.
065     *
066     * @return the predicate
067     * @since 3.1
068     */
069    public Predicate<? super T> getPredicate() {
070        return iPredicate;
071    }
072
073    /**
074     * Transforms the input to result by calling a predicate.
075     *
076     * @param input  the input object to transform
077     * @return the transformed result
078     */
079    @Override
080    public Boolean transform(final T input) {
081        return Boolean.valueOf(iPredicate.evaluate(input));
082    }
083
084}