All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.versionone.om.TransformIterable Maven / Gradle / Ivy

/*(c) Copyright 2008, VersionOne, Inc. All rights reserved. (c)*/
package com.versionone.om;

import java.util.ArrayList;
import java.util.Iterator;

public class TransformIterable implements Iterable {

    protected final Iterable wrapped;
    protected final ITransformerGeneric xform;
    protected final Class clazz;

    public TransformIterable(Iterable wrapped,
                             ITransformerGeneric xform, Class clazz) {
        this.wrapped = wrapped;
        this.xform = xform;
        this.clazz = clazz;
    }

    public Iterator iterator() {
        return new TransformIterator();
    }

    /**
     * Convert array from D type to type which set by {@code dClass} parameter.
     *
     * @return array with type {@code dClass}.
     */
    public Object[] toArray() {
        ArrayList l = new ArrayList();

        for (S o : wrapped) {
            l.add(xform.transform(o, clazz));
        }
        return l.toArray();
    }

    ////////////////////////////////// SubClasses //////////////////////////////

    public interface ITransformerGeneric {
        T transform(S s, Class dClass);
    }

    public interface ITransformer {
        T transform(S input);
    }

    class TransformIterator implements Iterator {
        private final Iterator wrappedIterator;

        public TransformIterator() {
            this.wrappedIterator = TransformIterable.this.wrapped.iterator();
        }

        public boolean hasNext() {
            return this.wrappedIterator.hasNext();
        }

        public D next() {
            return xform.transform(this.wrappedIterator.next(), clazz);
        }

        public void remove() {
            this.wrappedIterator.remove();
        }
    }
}