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.io.Serializable;
020import java.util.Iterator;
021
022import org.apache.commons.functor.BinaryProcedure;
023import org.apache.commons.functor.UnaryPredicate;
024
025/**
026 * Remove elements from left Iterator that match right UnaryPredicate.
027 *
028 * @param <T> the procedure argument type.
029 * @version $Revision: 1344796 $ $Date: 2012-05-31 12:12:39 -0400 (Thu, 31 May 2012) $
030 */
031public final class RemoveMatching<T>
032    implements BinaryProcedure<Iterator<? extends T>, UnaryPredicate<? super T>>, Serializable {
033    /**
034     * serialVersionUID declaration.
035     */
036    private static final long serialVersionUID = -8376577687898040683L;
037    /**
038     * A static {@link RemoveMatching} instance reference.
039     */
040    private static final RemoveMatching<Object> INSTANCE = new RemoveMatching<Object>();
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        while (left.hasNext()) {
049            if (right.test(left.next())) {
050                left.remove();
051            }
052        }
053    }
054
055    /**
056     * {@inheritDoc}
057     */
058    @Override
059    public boolean equals(Object obj) {
060        return obj == this || obj != null && obj.getClass().equals(getClass());
061    }
062
063    /**
064     * {@inheritDoc}
065     */
066    @Override
067    public int hashCode() {
068        return System.identityHashCode(INSTANCE);
069    }
070
071    /**
072     * {@inheritDoc}
073     */
074    @Override
075    public String toString() {
076        return "RemoveMatching";
077    }
078
079    /**
080     * Get a static {@link RemoveMatching} instance.
081     * @return {@link RemoveMatching}
082     */
083    public static RemoveMatching<Object> instance() {
084        return INSTANCE;
085    }
086
087}