Skip to content

Instantly share code, notes, and snippets.

@iyengarajay

iyengarajay/FunctionalChaining.java Secret

Last active Aug 19, 2016
Embed
What would you like to do?
import java.util.function.Function;
import java.util.stream.Stream;
public class FunctionalChaining {
public static void main(String[] args)
{
Function<Double, Double> func1 = d -> d + 0.2;
Function<Double, Double> func2 = d -> d + 0.5;
// Simple chaining
System.out.println(func1.andThen(func2).apply(1.0));
// Chaining using Stream.of
Function<Double, Double> combined = Stream.of(func1, func2)
.reduce(Function.identity(), Function::andThen);
System.out.println(combined.apply(1.0));
// Pass it to a function which can accept variable number of functions.
System.out.println(combineFunctions(func1, func2));
}
private static Double combineFunctions(Function<Double, Double>... combineFunctions)
{
Function<Double, Double> chainedFunction = Stream.of(combineFunctions)
.reduce(function -> function,Function::andThen);
return chainedFunction.apply(1.0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment