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

Type Inference with Generics

How the compiler infers generic type parameters in lambda expressions from the target functional interface.

Type Inference with Generics

You'll learn how Java's compiler automatically figures out the generic type parameters in your lambda expressions by examining the functional interface you're targeting.

Understanding the Magic Behind the Scenes

When you write a lambda expression, you rarely need to spell out generic type parameters explicitly—Java infers them for you. The compiler looks at the target functional interface (the interface your lambda is being assigned to or passed as) and extracts the generic types from its declaration.

For example, when you use Function<String, Integer>, the compiler knows the lambda's input must be String and output must be Integer. You don't need to write (String s) -> s.length(); you can simply write s -> s.length(), and the compiler fills in the blanks.

How It Works

The compiler uses the generic type information from:

  • The functional interface's generic declaration
  • The method signature you're passing the lambda to
  • The variable declaration or assignment context

This is why you can write concise code like:

Function<String, Integer> lengthFn = str -> str.length();

The Function<String, Integer> tells the compiler that str is a String, so you get type safety without typing extra characters.

With BiFunction:

BiFunction<Integer, Integer, Integer> adder = (a, b) -> a + b;

The compiler infers that a and b are both Integer based on the BiFunction<Integer, Integer, Integer> target type.

The Diamond Operator Connection

This is similar to how List<String> list = new ArrayList<>(); works—the compiler infers <String> on the right side from the left.

Key Takeaway: The compiler infers generic types in lambda parameters by examining the target functional interface's generic declarations, allowing you to write concise, type-safe lambdas without redundant type annotations.