Java 8 : BiFunction Functional Interface
BiFunction
A BiFunction is a Function that accepts two arguments and produces a result.
The difference with Function is that while a Function takes a single parameter, a BiFunction takes 2 arguments.
@FunctionalInterface public class BiFuntion<T, U, R> {
R apply(T t, U u); // Performs this operation on the given argument.
}
Example 1 : BiFunction
package com.topjavatutorial; import java.util.function.BiFunction; import java.util.function.Function; public class TestBiFunction { public static void main(String[] args) { Function<String, Integer> f1 = str -> str.length(); System.out.println(f1.apply("TopJavaTutorial")); BiFunction<String, String, String> f2 = (str1, str2) -> str1.concat(str2); System.out.println(f2.apply("TopJavaTutorial", ".com")); } }
Output :
15
TopJavaTutorial.com
Example 2 : BiFunction with Method Reference
package com.topjavatutorial; import java.util.function.BiFunction; import java.util.function.Function; public class TestBiFunction { public static void main(String[] args) { Function<String, Integer> f1 = String::length; System.out.println(f1.apply("TopJavaTutorial")); BiFunction<String, String, String> f2 = String::concat; System.out.println(f2.apply("TopJavaTutorial", ".com")); } }
Output :
15
TopJavaTutorial.com
BiFunction default method andThen()
default <V> BiFunction<T,U,V> andThen(Function<? super R,? extends V> after)
andThen() returns a composed function that first applies this function to its input, and then applies the after function to the result.
Example : BiFunction andThen()
In this example, the output of BiFunction f2 is chained to the function f1 and the result is displayed.
f2 concatenates the strings and f2 evaluates the length of the combined string.
package com.topjavatutorial; import java.util.function.BiFunction; import java.util.function.Function; public class TestBiFunction { public static void main(String[] args) { Function<String, Integer> f1 = String::length; BiFunction<String, String, String> f2 = String::concat; // BiFunction example System.out.println(f2.andThen(f1).apply("TopJavaTutorial", ".com")); } }
Output :
19
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post