Course contentsShow
← Java
Lesson 1630 of 2,87035. Functional InterfacesFree lesson

Creating Custom Functional Interfaces

When and how to define your own functional interfaces for domain-specific lambda targets.

Creating Custom Functional Interfaces

You'll learn when and how to define your own functional interfaces for domain-specific lambda targets.

While java.util.function provides common interfaces like Predicate, Function, and Consumer, you'll often encounter domain-specific scenarios where creating your own functional interface makes your code more expressive and type-safe.

Why Create Custom Functional Interfaces?

Think of custom functional interfaces as creating your own vocabulary. Instead of saying "this takes a Function," you might say "this takes a PriceCalculator" or "this takes a ValidationRule." Your code becomes self-documenting and harder to misuse.

How to Create One

Simply define an interface with exactly one abstract method and annotate it with @FunctionalInterface:

@FunctionalInterface
public interface OrderValidator {
    boolean validate(Order order);
}

The @FunctionalInterface annotation isn't mandatory, but it's highly recommended—it tells the compiler to verify you have exactly one abstract method, catching mistakes early.

Using Your Custom Interface

public class OrderService {
    public List<Order> filterOrders(List<Order> orders, OrderValidator validator) {
        return orders.stream()
                     .filter(order -> validator.validate(order))
                     .collect(Collectors.toList());
    }
}

// Usage with lambda
filterOrders(orders, order -> order.getTotal() > 100.0);

When to Create Custom Interfaces

Create your own when:

  • The domain concept is specific to your business (e.g., PricingStrategy, ShippingRule)
  • You want clearer API signatures than generic Function<T, R>
  • You need to add default or static helper methods specific to that operation

Key Takeaway: Custom functional interfaces let you create meaningful, type-safe lambda targets that express business concepts clearly—making your APIs more intuitive than generic Function or Predicate types.