Course contentsShow
← Java
Lesson 1728 of 2,87036. Lambda Expressions and Method ReferencesFree lesson

Target Type from Method Parameters

How the compiler determines a lambda's type when passed as a method argument.

Target Type from Method Parameters

You'll learn: How the Java compiler figures out what type your lambda expression should be when you pass it into a method.

The Core Idea

When you pass a lambda expression as an argument to a method, the compiler looks at the method's parameter type to determine what functional interface your lambda should implement. This is one of the most common ways target typing works in practice.

Think of it like fitting a puzzle piece into a slot: the shape of the slot (the method parameter type) tells you exactly what shape the piece (your lambda) needs to be.

How It Works

When you write something like:

list.forEach(item -> System.out.println(item));

The compiler:

  1. Sees forEach expects a Consumer<T> parameter
  2. Checks that your lambda item -> System.out.println(item) matches Consumer's abstract method signature
  3. Automatically treats your lambda as a Consumer implementation

Multiple Parameters Example

public void processList(Predicate<String> tester) {
    // uses tester
}

public void processList(Function<String, Integer> mapper) {
    // uses mapper
}

// Compiler uses parameter type to resolve overload:
processList(s -> s.isEmpty());        // Predicate (returns boolean)
processList(s -> s.length());         // Function (returns Integer)

The method signature eliminates ambiguity—the compiler knows which overloaded version you're calling based on what type your lambda returns.

Why This Matters

You don't have to explicitly cast or declare the lambda's type. The method parameter provides the target type context, making your code cleaner and more readable.

Key Takeaway: The compiler determines a lambda's functional interface type by examining the method parameter it's being passed to—the parameter signature provides all the context needed for type inference.