This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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