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

Type Inference Basics in Lambda Parameters

How the compiler infers lambda parameter types from the target functional interface without explicit declarations.

Type Inference Basics in Lambda Parameters

You'll learn how Java's compiler automatically determines lambda parameter types without requiring you to write them explicitly.

The Core Idea

When you write a lambda expression, Java already knows the target type—the functional interface your lambda must implement. Since each functional interface has exactly one abstract method with a defined signature, the compiler can deduce what types your lambda parameters must have. This means you rarely need to declare parameter types explicitly; the compiler infers them for you.

Think of it like ordering from a menu where each dish number corresponds to exactly one meal. If you say "I'll have #5," the waiter doesn't need you to describe the meal—they already know what #5 is. Similarly, when you provide a lambda to a Predicate<String>, Java knows your parameter must be a String.

How It Works

// The compiler knows filter expects Predicate<String>
// Predicate's test method takes a String parameter
// Therefore, s must be a String
list.stream()
    .filter(s -> s.length() > 3)
    .forEach(System.out::println);

You didn't write (String s) -> ..., but Java inferred s is a String by examining:

  1. The filter method expects Predicate<String>
  2. Predicate<String>'s abstract method is boolean test(String t)
  3. Therefore, your lambda's parameter must be String

This inference works with all functional interfaces, whether from java.util.function or your custom ones. The compiler traces backward from the context where your lambda is used.

When Inference Happens

Type inference activates whenever you omit parameter types in your lambda. It relies entirely on the target functional interface being clear from the surrounding code context.

Key Takeaway: The compiler infers lambda parameter types by examining the target functional interface's abstract method signature, eliminating the need for explicit type declarations in most cases.