Lambda Expression Formatting Best Practices
What you'll learn: How to format lambda expressions for maximum readability, distinguishing between simple one-liners and complex multi-statement blocks.
The Core Idea
Just because lambdas can fit on one line doesn't mean they always should. Formatting conventions help readers quickly distinguish trivial operations from complex logic. Think of it like punctuation in writing: proper formatting guides the reader's eye and brain.
Simple Lambda: Keep It Inline
When your lambda has a single, straightforward expression, keep it on one line:
// Clean and readable
list.forEach(item -> System.out.println(item));
numbers.stream()
.filter(n -> n > 10)
.map(n -> n * 2)
.collect(Collectors.toList());
The brevity signals "this is simple logic."
Complex Lambda: Use Block Format
When your lambda contains multiple statements, format it like a mini-method with clear structure:
list.forEach(item -> {
String formatted = item.toUpperCase();
System.out.println("Processing: " + formatted);
logger.log(formatted);
});
Notice the opening brace on the same line as the arrow, body indented, and closing brace aligned with the statement start.
Multiple Parameters: Align Thoughtfully
For multi-parameter lambdas with complex bodies, consider breaking the line after the arrow:
map.forEach((key, value) -> {
int computed = value * 2;
System.out.println(key + " = " + computed);
});
The Readability Test
Ask yourself: "Can someone understand this lambda's purpose in 2 seconds?" If not, expand to block format or extract to a method reference.
Key Takeaway: Format simple lambdas inline for brevity, but expand complex lambdas into block format with proper indentation—clarity always trumps compactness.