001/*-------------------------------------------------------------------------+
002|                                                                          |
003| Copyright 2005-2011 The ConQAT Project                                   |
004|                                                                          |
005| Licensed under the Apache License, Version 2.0 (the "License");          |
006| you may not use this file except in compliance with the License.         |
007| 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.conqat.lib.commons.predicate;
018
019import java.util.Arrays;
020import java.util.List;
021import java.util.function.Predicate;
022
023/**
024 * Predicate that combines other predicates with boolean "or". This supports
025 * lazy evaluation. This is immutable and stateless if the inner predicates are
026 * immutable and stateless.
027 * 
028 * @param <T>
029 *            the element type the predicate works on.
030 */
031public class OrPredicate<T> implements Predicate<T> {
032
033        /** The delegate predicates. */
034        private final List<Predicate<T>> innerPredicates;
035
036        /** Constructor. */
037        @SafeVarargs
038        public OrPredicate(Predicate<T>... innerPredicates) {
039                this.innerPredicates = Arrays.asList(innerPredicates);
040        }
041
042        /** {@inheritDoc} */
043        @Override
044        public boolean test(T element) {
045                for (Predicate<T> inner : innerPredicates) {
046                        if (inner.test(element)) {
047                                return true;
048                        }
049                }
050                return false;
051        }
052
053        /**
054         * Factory method for creating an or-predicate. This is used to exploit generic
055         * type inference (i.e. syntactic reasons).
056         */
057        @SafeVarargs
058        public static <T> OrPredicate<T> create(Predicate<T>... innerPredicates) {
059                return new OrPredicate<T>(innerPredicates);
060        }
061}