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.functor.core.algorithm;
018
019import java.util.Iterator;
020
021import org.apache.commons.functor.BinaryProcedure;
022import org.apache.commons.functor.Predicate;
023import org.apache.commons.functor.core.composite.Not;
024
025/**
026 * Retain elements in left Iterator that match right Predicate.
027 *
028 * @param <T> the procedure argument type
029 * @version $Revision: 1537906 $ $Date: 2013-11-01 12:47:33 +0100 (Fr, 01 Nov 2013) $
030 */
031public final class RetainMatching<T>
032    implements BinaryProcedure<Iterator<? extends T>, Predicate<? super T>> {
033    /**
034     * A static {@code RetainMatching} instance reference.
035     */
036    private static final RetainMatching<Object> INSTANCE = new RetainMatching<Object>();
037    /**
038     * The {@code RemoveMatching} instance used to remove elements from input iterator.
039     */
040    private final RemoveMatching<T> removeMatching = new RemoveMatching<T>();
041
042    /**
043     * {@inheritDoc}
044     * @param left {@link Iterator}
045     * @param right {@link Predicate}
046     */
047    public void run(Iterator<? extends T> left, Predicate<? super T> right) {
048        removeMatching.run(left, Not.not(right));
049    }
050
051    /**
052     * {@inheritDoc}
053     */
054    @Override
055    public boolean equals(Object obj) {
056        return obj == this || obj != null && obj.getClass().equals(getClass());
057    }
058
059    /**
060     * {@inheritDoc}
061     */
062    @Override
063    public int hashCode() {
064        return System.identityHashCode(INSTANCE);
065    }
066
067    /**
068     * {@inheritDoc}
069     */
070    @Override
071    public String toString() {
072        return "RetainMatching";
073    }
074
075    /**
076     * Get a static {@link RetainMatching} instance.
077     * @return {@link RetainMatching}
078     */
079    public static RetainMatching<Object> instance() {
080        return INSTANCE;
081    }
082}