Returns a List with the given functions applied using Lambda. - Java Lambda Stream

Java examples for Lambda Stream:Function

Description

Returns a List with the given functions applied using Lambda.

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

import java.util.function.Function;

public class Main {
    /** Returns a List with the given functions applied. The functions
     *  must all map their argument to an output of the SAME type (i.e., Function<T,T>).
     *///from   ww w .j a  v a  2 s .  c  o  m
    public static <T> List<T> transform2(List<T> origValues,
            Function<T, T>... transformers) {
        Function<T, T> composedFunction = composeAll(transformers);
        return (transform(origValues, composedFunction));
    }

    /** Returns composition of given functions. Given 0 or more functions,
     *  returns a new function that is a composition of them, in order. The functions
     *  must all map their argument to an output of the SAME type (i.e., Function<T,T>).
     */
    public static <T> Function<T, T> composeAll(Function<T, T>... functions) {
        Function<T, T> result = Function.identity();
        for (Function<T, T> f : functions) {
            result = result.compose(f);
        }
        return (result);
    }

    public static <T, R> List<R> transform(List<T> origValues,
            Function<T, R> transformer) {
        List<R> transformedValues = new ArrayList<>();
        for (T value : origValues) {
            transformedValues.add(transformer.apply(value));
        }
        return (transformedValues);
    }
}

Related Tutorials