How to apply a list of functions to a value in Java 8?

n0rm1e :

Let's say I have this imperative code:

    List<Function<T, T>> functions = ...
    T value = ...
    for (Function<T, T> function : functions) {
        value = function.apply(value);
    }

How do I write this in the functional style (like what fold does in Scala)?

Eugene :

This has just been asked a few hours ago for a Consumer... You could reduce them to a single function and apply that:

@SafeVarargs
private static <T> Function<T, T> combineF(Function<T, T>... funcs) {
    return Arrays.stream(funcs).reduce(Function.identity(), Function::andThen);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=440211&siteId=1