Skip to content

Instantly share code, notes, and snippets.

@bzah
Last active February 13, 2023 09:54
Show Gist options
  • Save bzah/20708d5001a5500febffe03101435db6 to your computer and use it in GitHub Desktop.
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 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 [email protected]
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