Advertisement
Advanced Java, Functional Interfaces & Method References

How would you implement a custom functional interface with generic type parameters, and what considerations apply when designing one instead of reusing a built-in java.util.function interface?

Short answer

A custom functional interface is warranted specifically when a built-in interface's method name and semantic meaning wouldn't clearly communicate the interface's actual purpose in your domain (a domain-specific name like OrderValidator improves readability over a generic…

Save Java mock interview
Advertisement
AModel answer
A custom functional interface is warranted specifically when a built-in interface's method name and semantic meaning wouldn't clearly communicate the interface's actual purpose in your domain (a domain-specific name like OrderValidator improves readability over a generic Predicate<Order>), or when you need a functional method with more than two parameters or a checked exception in its signature (which none of the standard java.util.function interfaces support directly) -- when designing one, marking it with @FunctionalInterface, keeping exactly one abstract method, and following the standard naming convention of an -er or descriptive verb-based name helps it integrate naturally alongside the JDK's own functional interfaces.
@FunctionalInterface
public interface TriFunction<A, B, C, R> {
    R apply(A a, B b, C c);  // built-in Function/BiFunction only support 1 or 2 parameters
}

TriFunction<Integer, Integer, Integer, Integer> sum3 = (a, b, c) -> a + b + c;
System.out.println(sum3.apply(1, 2, 3));  // 6
Real-world example
A pricing calculation needing three inputs (base price, discount rate, tax rate) defines a custom TriFunction interface since none of the standard java.util.function interfaces support a three-argument function signature, filling a genuine gap in the built-in library's coverage.
Likely follow-ups
  • Why does the standard library stop at BiFunction and not provide TriFunction/QuadFunction built in?
  • How would you design a functional interface whose method needs to declare a checked exception, given standard functional interfaces don't support this?
Related topics