Working with Lambda Expressions
1. Understanding Lambda Syntax
| Form | Example |
|---|---|
| No params | () -> 42 |
| Single param | x -> 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
| Aspect | Detail |
|---|---|
| Parens optional | Only with single inferred param |
| Return type | Inferred 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);
| Rule | Detail |
|---|---|
| Parentheses | Required |
| Type uniformity | All params must use var together or none |
4. Using Block Lambdas
| Form | Detail |
|---|---|
| Body | { ... } |
| Return | Explicit return needed for non-void |
5. Understanding Effectively Final Variables
| Aspect | Detail |
|---|---|
| Definition | Local var assigned once, never modified |
| Usage in lambda | Captured by reference |
| Workaround for mutation | Use single-element array or AtomicReference |
6. Using Method References (Class::method)
| Form | Equivalent |
|---|---|
String::length | s -> s.length() |
System.out::println | x -> System.out.println(x) |
Integer::parseInt | Static method |
String::compareToIgnoreCase | Unbound 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);
| Form | Use |
|---|---|
ClassName::new | Constructor |
Type[]::new | Array constructor |
8. Understanding Target Typing
| Source | Detail |
|---|---|
| Variable assignment | Runnable r = () -> ... |
| Method argument | Inferred from parameter type |
| Cast | (Comparator<String>) (a,b) -> ... |
9. Using Lambda with Collections
| API | Use |
|---|---|
list.removeIf(p) | Predicate-based remove |
list.replaceAll(op) | UnaryOperator transform |
map.forEach(bc) | BiConsumer iteration |
map.compute/merge | BiFunction update |
10. Replacing Anonymous Classes with Lambdas
| Anonymous | Lambda |
|---|---|
new Comparator<String>(){ public int compare(...){...} } | (a,b) -> ... |
| Multiple methods | Cannot convert |
this binding | Anonymous = self; lambda = enclosing |
11. Understanding Lambda Variable Scope
| Element | Behavior |
|---|---|
| Parameters | Cannot shadow enclosing variables |
| Captured locals | Must be effectively final |
this | Refers to enclosing instance |