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     */
017    package org.apache.commons.functor.core.algorithm;
018    
019    import java.io.Serializable;
020    import java.util.Iterator;
021    
022    import org.apache.commons.functor.BinaryProcedure;
023    import org.apache.commons.functor.UnaryPredicate;
024    import org.apache.commons.functor.core.composite.UnaryNot;
025    
026    /**
027     * Retain elements in left Iterator that match right UnaryPredicate.
028     *
029     * @version $Revision: 1166328 $ $Date: 2011-09-07 21:32:26 +0200 (Wed, 07 Sep 2011) $
030     */
031    public final class RetainMatching<T>
032        implements BinaryProcedure<Iterator<? extends T>, UnaryPredicate<? super T>>, Serializable {
033        /**
034         * serialVersionUID declaration.
035         */
036        private static final long serialVersionUID = 6760018011875465469L;
037    
038        private static final RetainMatching<Object> INSTANCE = new RetainMatching<Object>();
039    
040        private RemoveMatching<T> removeMatching = new RemoveMatching<T>();
041    
042        /**
043         * {@inheritDoc}
044         * @param left {@link Iterator}
045         * @param right {@link UnaryPredicate}
046         */
047        public void run(Iterator<? extends T> left, UnaryPredicate<? super T> right) {
048            removeMatching.run(left, UnaryNot.not(right));
049        }
050    
051        /**
052         * {@inheritDoc}
053         */
054        public boolean equals(Object obj) {
055            return obj == this || obj != null && obj.getClass().equals(getClass());
056        }
057    
058        /**
059         * {@inheritDoc}
060         */
061        public int hashCode() {
062            return System.identityHashCode(INSTANCE);
063        }
064    
065        /**
066         * Get a static {@link RetainMatching} instance.
067         * @return {@link RetainMatching}
068         */
069        public static RetainMatching<Object> instance() {
070            return INSTANCE;
071        }
072    }