Last active
February 13, 2023 09:54
-
-
Save bzah/20708d5001a5500febffe03101435db6 to your computer and use it in GitHub Desktop.
Pipe multiple functional calls in java. In the example the operations are on Integers.
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
// This code is licensed under the terms of the APACHE 2 License (https://www.apache.org/licenses/LICENSE-2.0.html) | |
// Copyright (C) 2023 Aoun Abel aoun.abel@gmail.com | |
public class FunctionalPipe { | |
public static <T> T pipe(T value, | |
Function<? super T, ? extends T>... functions) { | |
Function<T, T> accumulator = Function.identity(); | |
for (Function<? super T, ? extends T> function : functions) | |
accumulator = accumulator.compose(function); | |
return accumulator.apply(value); | |
} | |
} | |
public class FunctionalPipeTest { | |
@Test | |
public void pipe_shouldWork() { | |
Function<Integer, Integer> increment = (a) -> a + 1; | |
Integer res = FunctionalPipe.pipe( | |
1, | |
increment, | |
add(2) | |
); | |
Assert.assertEquals(new Integer(4), res); | |
} | |
private Function<Integer, Integer> add(Integer integer){ | |
Function<Integer, Function<Integer, Integer>> addf = a -> b -> a + b; | |
return addf.apply(integer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment