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 implements Converter {

    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) {
        this.itemConverter = itemConverter;
        this.collectionType = collectionType;
    }

    @Override
    public Collection convert(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();
    }

    @Override
    public Class sourceType() {
        return Collection.class;
    }

    @Override
    public Class targetType() {
        return Collection.class;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy