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 015 package org.apache.commons.functor.generator.util; 016 017 import java.util.ArrayList; 018 import java.util.Collection; 019 020 import org.apache.commons.functor.UnaryFunction; 021 import org.apache.commons.functor.UnaryProcedure; 022 import org.apache.commons.functor.generator.Generator; 023 024 /** 025 * Transforms a generator into a collection. If a collection is not passed into 026 * the constructor an ArrayList will be returned from the transform method. 027 * 028 * @param <E> the type of elements held in the adapted collection. 029 * @since 1.0 030 * @version $Revision: 1160793 $ $Date: 2011-08-23 18:48:32 +0200 (Tue, 23 Aug 2011) $ 031 * @author Jason Horman (jason@jhorman.org) 032 */ 033 public class CollectionTransformer<E> implements UnaryFunction<Generator<? extends E>, Collection<? super E>> { 034 /* 035 * TODO revisit this class... it could stand a more-descriptive name. Also, it's a little 036 * hard to say whether, for an instance constructed without a specific target collection, 037 * #evaluate() should return a new ArrayList for each call, or continue adding to 038 * a single ArrayList instance (the current behavior). 039 * Perhaps this is more a documentation issue than anything. 040 */ 041 042 // instance methods 043 //--------------------------------------------------- 044 /** 045 * The adapted collection has to be filled. 046 */ 047 private final Collection<? super E> toFill; 048 049 // constructors 050 //--------------------------------------------------- 051 /** 052 * Create a new CollectionTransformer. 053 */ 054 public CollectionTransformer() { 055 this(null); 056 } 057 058 /** 059 * Create a new CollectionTransformer. 060 * @param toFill Collection to fill 061 */ 062 public CollectionTransformer(Collection<? super E> toFill) { 063 Collection<? super E> coll; 064 if (toFill == null) { 065 coll = new ArrayList<E>(); 066 } else { 067 coll = toFill; 068 } 069 this.toFill = coll; 070 } 071 072 // instance methods 073 //--------------------------------------------------- 074 /** 075 * {@inheritDoc} 076 */ 077 @SuppressWarnings("unchecked") 078 public Collection<E> evaluate(Generator<? extends E> generator) { 079 generator.run(new UnaryProcedure<E>() { 080 public void run(E obj) { 081 toFill.add(obj); 082 } 083 }); 084 return (Collection<E>) toFill; 085 } 086 }