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

Parentheses Rules for Single Parameters

When parentheses can be omitted for single-parameter lambdas and when they are required.

Parentheses Rules for Single Parameters

You'll learn exactly when you can skip parentheses around single-parameter lambdas and when Java requires them.

The Core Rule

When your lambda expression has exactly one parameter and you're using type inference (not explicitly declaring the type), you can omit the parentheses around that parameter. It's a syntactic shortcut that makes your code cleaner.

However, if you explicitly declare the parameter type, parentheses become mandatory—even for a single parameter.

When Parentheses Are Optional

// Without parentheses (allowed)
Consumer<String> printer = s -> System.out.println(s);
Predicate<Integer> isEven = n -> n % 2 == 0;
Function<String, Integer> length = str -> str.length();

When Parentheses Are Required

// With explicit type - parentheses required
Consumer<String> printer = (String s) -> System.out.println(s);
Predicate<Integer> isEven = (Integer n) -> n % 2 == 0;

// Multiple parameters - always need parentheses
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;

// Zero parameters - always need parentheses
Supplier<Double> random = () -> Math.random();

The var Exception (Java 11+)

// Even with 'var', parentheses are required
Consumer<String> printer = (var s) -> System.out.println(s);

Think of it like this: parentheses are the "formal dress code" for parameters. When you have a single parameter and keep it casual (no type declaration), Java lets you skip the formality. But the moment you dress it up with a type (or use var), you need the full formal syntax.

Key Takeaway: Omit parentheses only for single parameters with inferred types; use parentheses when declaring explicit types, using var, or having zero/multiple parameters.