Returns a new Collection consisting of the elements of the input collection transformed by the given transformer. - Java java.util

Java examples for java.util:Collection Creation

Description

Returns a new Collection consisting of the elements of the input collection transformed by the given transformer.

Demo Code


import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class Main{
    /**//from w w w.  j  a  v  a2  s.  co m
     * Returns a new Collection consisting of the elements of the input
     * collection transformed by the given transformer.
     * <p>
     *
     * @param <I> the type of object in the input collection.
     * @param <O> the type of object in the output collection.
     * @param col the collection to get the input from, may be null.
     * @param mapper the mapper to use.
     * @return the transformed result (new list).
     * @throws NullPointerException if the mapper is null.
     */
    public static <I, O> List<O> map(Iterable<I> col,
            Mapper<? super I, ? extends O> mapper) {
        if (col == null) {
            return null;
        }
        if (mapper == null) {
            throw new NullPointerException("The 'mapper' argument is NULL");
        }
        int size = (col instanceof Collection) ? ((Collection) col).size()
                : 0;
        ArrayList<O> result = new ArrayList<O>(size);
        for (I input : col) {
            O output = mapper.map(input);
            result.add(output);
        }
        return result;
    }
}

Related Tutorials