Java.Java8.What is the functional interface BiFunction?

Excellent question! Let’s break down the BiFunction<T, U, R> functional interface — one of the most versatile tools in Java functional programming.


BiFunction<T, U, R>

@FunctionalInterface
public interface BiFunction<T, U, R> {
    R apply(T t, U u);
}
  • Takes two inputs: T and U
  • Produces a result of type R
  • It’s the two-argument version of Function<T, R>

🧠 Example:

BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(5, 7)); // Output: 12

Another example with different types:

BiFunction<String, Integer, String> repeat = (s, times) -> s.repeat(times);
System.out.println(repeat.apply("Hi", 3)); // Output: HiHiHi

🔧 Real Use Case: Converting key-value pairs

Map<String, Integer> map = new HashMap<>();
map.put("apple", 2);
map.put("banana", 3);

// Convert map entries using BiFunction
map.replaceAll((k, v) -> v * 10); // BiFunction<String, Integer, Integer>
System.out.println(map); // {apple=20, banana=30}

🔗 Chaining BiFunctions with .andThen()

You can chain a BiFunction with a Function<R, V> using .andThen():

BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b;
Function<Integer, String> stringify = i -> "Result: " + i;

String result = multiply.andThen(stringify).apply(3, 4);
System.out.println(result); // Output: Result: 12

✅ Summary

InterfaceInput TypesOutput TypeExample
BiFunction<T,U,R>T, UR(a, b) -> a + b, (s, n) -> s.repeat(n)

This entry was posted in Без рубрики. Bookmark the permalink.