https://github.com/ahlusar1989/java-workshop-materials
https://ahlusar1989.github.io/java-workshop-materials/
All code examples in examples.basics.composition.FunctionCompositionTest.java
BiFunction Functional Interface
// create a basic concatenation function
private BiFunction<String, String, String> concat = (a, b) -> a + " " + b;
@Test
public void testConcat() {
String phrase = concat.apply("Hello", "Fred");
assertThat(phrase).isEqualTo("Hello Fred");
}
Function and BiFunction Functional Interfaces
// create a basic concatenation function
private BiFunction<String, String, String> concat = (a, b) -> a + " " + b;
// create a new function that calls the concatenation function, but
// provides the first parameter as a constant
private Function<String, String> hello = a -> concat.apply("Hello", a);
@Test
public void testHello() {
String phrase = hello.apply("Fred");
assertThat(phrase).isEqualTo("Hello Fred");
}
"composed" Functions are Useful in Stream Pipelines
// create a basic concatenation function
private BiFunction<String, String, String> concat = (a, b) -> a + " " + b;
// create a new function that calls the concatenation function, but
// provides the first parameter as a constant
private Function<String, String> hello = a -> concat.apply("Hello", a);
@Test
public void testHelloInStream() {
String answer = Stream.of(ImmutableUser.of("Fred", "Flintstone"),
ImmutableUser.of("Barney", "Rubble"))
.map(ImmutableUser::getFirstName)
.map(hello)
.collect(Collectors.joining(", "));
assertThat(answer).isEqualTo("Hello Fred, Hello Barney");
}