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.generator;
018
019 import org.apache.commons.functor.UnaryFunction;
020 import org.apache.commons.functor.UnaryProcedure;
021
022 /**
023 * Generator that transforms the elements of another Generator.
024 *
025 * @version $Revision: 1156799 $ $Date: 2011-08-11 22:11:54 +0200 (Thu, 11 Aug 2011) $
026 */
027 public class TransformedGenerator<I, E> extends BaseGenerator<E> {
028 private final UnaryFunction<? super I, ? extends E> func;
029
030 /**
031 * Create a new TransformedGenerator.
032 * @param wrapped Generator to transform
033 * @param func UnaryFunction to apply to each element
034 */
035 public TransformedGenerator(Generator<? extends I> wrapped, UnaryFunction<? super I, ? extends E> func) {
036 super(wrapped);
037 if (wrapped == null) {
038 throw new IllegalArgumentException("Generator argument was null");
039 }
040 if (func == null) {
041 throw new IllegalArgumentException("UnaryFunction argument was null");
042 }
043 this.func = func;
044 }
045
046 /**
047 * {@inheritDoc}
048 */
049 public void run(final UnaryProcedure<? super E> proc) {
050 getWrappedGenerator().run(new UnaryProcedure<I>() {
051 public void run(I obj) {
052 proc.run(func.evaluate(obj));
053 }
054 });
055 }
056
057 /**
058 * {@inheritDoc}
059 */
060 @SuppressWarnings("unchecked")
061 @Override
062 protected Generator<? extends I> getWrappedGenerator() {
063 return (Generator<? extends I>) super.getWrappedGenerator();
064 }
065
066 /**
067 * {@inheritDoc}
068 */
069 public boolean equals(Object obj) {
070 if (obj == this) {
071 return true;
072 }
073 if (!(obj instanceof TransformedGenerator<?, ?>)) {
074 return false;
075 }
076 TransformedGenerator<?, ?> other = (TransformedGenerator<?, ?>) obj;
077 return other.getWrappedGenerator().equals(getWrappedGenerator()) && other.func == func;
078 }
079
080 /**
081 * {@inheritDoc}
082 */
083 public int hashCode() {
084 int result = "TransformedGenerator".hashCode();
085 result <<= 2;
086 result ^= getWrappedGenerator().hashCode();
087 result <<= 2;
088 result ^= func.hashCode();
089 return result;
090 }
091 }