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

cz.jalasoft.lifeconfig.converter.CollectionConverter Maven / Gradle / Ivy

package cz.jalasoft.lifeconfig.converter;

import java.util.*;
import java.util.function.Supplier;

/**
 * A converter that transforms a collection of objects
 * to another collection of another type of objects
 * based on provided converter of particular items.
 *
 * @author Honza Lastovicka ([email protected])
 * @since 2016-09-10.
 */
public final class CollectionConverter extends TypesafeConverter {

    private static final Map, Supplier> collectionFactory;

    static {
        collectionFactory = new HashMap<>();
        collectionFactory.put(Collection.class, () -> new ArrayList());
        collectionFactory.put(List.class, () -> new ArrayList());
        collectionFactory.put(Set.class, () -> new HashSet<>());
        collectionFactory.put(Queue.class, () -> new LinkedList());
    }

    //----------------------------------------------------------------------
    //INSTANCE SCOPE
    //----------------------------------------------------------------------

    private final Converter itemConverter;
    private final Class collectionType;

    public CollectionConverter(Converter itemConverter, Class collectionType) {
        super(Collection.class, Collection.class);

        this.itemConverter = itemConverter;
        this.collectionType = collectionType;
    }

    @Override
    protected Collection convertSafely(Collection from) throws ConverterException {
        Collection result = newCollection();

        for(Object element : from) {
            Object convertedElement = itemConverter.convert(element);
            result.add(convertedElement);
        }

        return result;
    }

    private Collection newCollection() {
        Supplier factory = collectionFactory.get(collectionType);
        return factory.get();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy