Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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)?

like image 838
n0rm1e Avatar asked Jun 13 '17 11:06

n0rm1e


People also ask

How can I turn a list of lists into a list in Java 8?

You can use the flatMap function to convert a list of lists to a big list containing all elements from individual lists. 5. Similar to the map function, flatMap is also an intermediate operation which means you can call other stream methods after calling this one.

Can we print list directly in Java?

The “toString()” method can be used to print a list in Java. This method prints the specified list elements directly using their references.


1 Answers

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);
}
like image 158
Eugene Avatar answered Oct 22 '22 07:10

Eugene