Working with Lambda Expressions

1. Understanding Lambda Syntax

FormExample
No params() -> 42
Single paramx -> x * 2
Typed params(int x, int y) -> x + y
Block body(x) -> { return x*x; }
var params(var x, var y) -> x+y (Java 11+, allows annotations)

2. Creating Single-Parameter Lambdas

AspectDetail
Parens optionalOnly with single inferred param
Return typeInferred from expression

3. Creating Multi-Parameter Lambdas

Example: Multi-param

BinaryOperator<Integer> add = (a, b) -> a + b;
BiFunction<String, Integer, String> repeat = (s, n) -> s.repeat(n);
RuleDetail
ParenthesesRequired
Type uniformityAll params must use var together or none

4. Using Block Lambdas

FormDetail
Body{ ... }
ReturnExplicit return needed for non-void

5. Understanding Effectively Final Variables

AspectDetail
DefinitionLocal var assigned once, never modified
Usage in lambdaCaptured by reference
Workaround for mutationUse single-element array or AtomicReference

6. Using Method References (Class::method)

FormEquivalent
String::lengths -> s.length()
System.out::printlnx -> System.out.println(x)
Integer::parseIntStatic method
String::compareToIgnoreCaseUnbound instance method

7. Using Constructor References (Class::new)

Example: Constructor reference

Supplier<List<String>> listFactory = ArrayList::new;
Function<String, User> createUser = User::new;
String[] names = stream.toArray(String[]::new);
FormUse
ClassName::newConstructor
Type[]::newArray constructor

8. Understanding Target Typing

SourceDetail
Variable assignmentRunnable r = () -> ...
Method argumentInferred from parameter type
Cast(Comparator<String>) (a,b) -> ...

9. Using Lambda with Collections

APIUse
list.removeIf(p)Predicate-based remove
list.replaceAll(op)UnaryOperator transform
map.forEach(bc)BiConsumer iteration
map.compute/mergeBiFunction update

10. Replacing Anonymous Classes with Lambdas

AnonymousLambda
new Comparator<String>(){ public int compare(...){...} }(a,b) -> ...
Multiple methodsCannot convert
this bindingAnonymous = self; lambda = enclosing

11. Understanding Lambda Variable Scope

ElementBehavior
ParametersCannot shadow enclosing variables
Captured localsMust be effectively final
thisRefers to enclosing instance