001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *      http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014
015package org.apache.commons.functor.generator.util;
016
017import java.util.ArrayList;
018import java.util.Collection;
019
020import org.apache.commons.functor.Function;
021import org.apache.commons.functor.Procedure;
022import org.apache.commons.functor.generator.Generator;
023import org.apache.commons.lang3.Validate;
024
025/**
026 * Transforms a generator into a collection.
027 *
028 * @param <E> the type of elements held in the adapted collection.
029 * @param <C> the type of the adapted collection
030 * @since 1.0
031 * @version $Revision: 1541614 $ $Date: 2013-11-13 18:06:01 +0100 (Mi, 13 Nov 2013) $
032 */
033public class CollectionTransformer<E, C extends Collection<? super E>> implements Function<Generator<? extends E>, C> {
034
035    // instance methods
036    //---------------------------------------------------
037    /**
038     * The adapted collection has to be filled.
039     */
040    private final C toFill;
041
042    // constructors
043    //---------------------------------------------------
044    /**
045     * Create a new CollectionTransformer.
046     * @param toFill Collection to fill
047     * @throws NullPointerException if the collection is {@code null}
048     */
049    public CollectionTransformer(C toFill) {
050        this.toFill = Validate.notNull(toFill, "toFill");
051    }
052
053    // instance methods
054    //---------------------------------------------------
055    /**
056     * Run the {@link Generator} adding each element produced into the
057     * collection.
058     * @param generator the generator
059     * @return the C collection filled with the elements produced by the generator
060     */
061    public C evaluate(Generator<? extends E> generator) {
062        generator.run(new Procedure<E>() {
063            public void run(E obj) {
064                toFill.add(obj);
065            }
066        });
067        return toFill;
068    }
069
070    /**
071     * Get a {@link CollectionTransformer} instance that simply returns any {@link Collection}.
072     * @param <E> the collection type
073     * @return {@link CollectionTransformer}
074     */
075    public static <E> CollectionTransformer<E, Collection<E>> toCollection() {
076        return new CollectionTransformer<E, Collection<E>>(new ArrayList<E>());
077    }
078}