Skip to content

Commit 057bde3

Browse files
committed
feat(Lambda): add Advanced Java Lambda Expressions tutorial with 10 examples
What - Added a single-file tutorial (conceptual) covering 10 advanced lambda/functional examples: 1. Returning complex objects from Supplier lambda (Person). 2. Using Comparator with lambda for custom sorting of objects. 3. Chaining Predicates with and(), or(), negate(). 4. Function chaining using andThen() and compose(). 5. Handling exceptions inside lambdas with try-catch. 6. Parallel streams combined with lambda map/forEach. 7. Defining and using a custom functional interface annotated with @FunctionalInterface. 8. Grouping with Stream.collect(Collectors.groupingBy()). 9. Using Optional with lambda-style callbacks and fallbacks. 10. Combining stream operations (filter, map, reduce) to compute aggregated results. - Each example includes short code, expected output, and a brief explanation. Why - Demonstrates practical, idiomatic uses of Java lambdas and functional APIs beyond trivial examples. - Teaches common patterns developers need for modern Java: Suppliers, Comparators, Predicates, Functions, Optional, Streams, Collectors, and parallelism. - Helps readers understand trade-offs (e.g., orElse vs orElseGet, cost of parallel streams, exception handling choices). - Serves as a compact reference for interviews, onboarding, or quick refreshers. How - Present each example as a self-contained code snippet with explanation and sample output. - Use standard java.util.function interfaces (Supplier, Predicate, Function, Comparator) and java.util.stream APIs. - Show safe patterns: Optional usage, try-catch inside lambdas for parsing, and prefer method references where concise. - Call out parallel stream caveats (non-deterministic order, suitability for large, CPU-bound tasks). - Recommend small pragmatic tips inline (use orElseGet for lazy defaults, prefer Collectors.groupingBy for grouping, annotate custom interfaces with @FunctionalInterface). Logic - Inputs: representative hardcoded data per example (lists of Person, integers, strings) to keep demos deterministic. - Outputs: printed console lines demonstrating behavior (shown with each snippet). - Flow (typical per example): 1. Create data source (List, Optional, Supplier, etc.). 2. Apply functional operation(s) (map, filter, sort, group, reduce). 3. Collect or consume results (forEach, System.out.println, orElse fallback). - Edge cases and considerations: - Exception handling: lambdas cannot declare checked exceptions; use try-catch or wrap checked exceptions. - Optional: avoid using Optional as fields or in serialization; prefer for return types. - Parallel streams: beware of thread-safety in lambdas and non-associative operations. - orElse eagerly evaluates its argument; for expensive defaults use orElseGet. - Comparator lambdas should avoid subtraction for numeric compare; use Integer.compare to avoid overflow. - Complexity / performance: - Most examples are O(n) or O(n log n) depending on sort/collect operations. - Parallel streams can improve throughput for large datasets but add coordination overhead. - Concurrency / thread-safety: - Demonstrate that lambdas are typically stateless; if capturing mutable state, document synchronization needs. - When using parallelStream, show immutable/side-effect-free operations for correctness. - Error handling: - Examples show graceful fallback (e.g., parse fallback to 0) and patterns for safe defaults. Real-life applications - Factory patterns and dependency injection using Suppliers. - Sorting domain objects in UI or reporting pipelines. - Validations and composite rules using Predicate chains. - Building ETL or transformation pipelines with Function chaining and Streams. - Safe parsing of untrusted input with lambda-embedded try-catch. - Parallel data processing for large collections (analytics, batch jobs). - Grouping and aggregation for reporting and dashboards using Collectors. - Using Optional to reduce null-related bugs in service/repository APIs. Notes - Prefer method references (Class::method) for readability when possible. - Annotate custom single-abstract-method interfaces with @FunctionalInterface to make intent explicit. - Avoid returning Optional from collections or using Optional in fields; use it as a return type from methods. - For deterministic ordering with parallel operations, ensure reduction is associative and combine functions are correct. - This tutorial is intentionally example-driven; production code should include tests, benchmarking for parallelism, and careful resource handling. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 0404c71 commit 057bde3

File tree

1 file changed

+23
-46
lines changed

1 file changed

+23
-46
lines changed

JAVA8/LambdaExpression/src/Advanced Java Lambda Expressions Cheat Sheet.txt renamed to Java 8 Crash Course/Lambda Expression/src/Advanced Java Lambda Expressions.txt

Lines changed: 23 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
Advanced Java Lambda Expressions Cheat Sheet
2-
3-
4-
✅ 1. Return Complex Objects
1+
Advanced Java Lambda Expressions:
52

3+
1. Return Complex Objects
64
You can return objects from lambda expressions.
75

86
import java.util.function.*;
@@ -24,12 +22,10 @@ public class LambdaDemo {
2422
}
2523
}
2624

27-
✅ Output:
28-
25+
Output:
2926
Alice
3027

31-
✅ 2. Using Comparator for Custom Sorting
32-
28+
2. Using Comparator for Custom Sorting
3329
Sort custom objects using lambdas with the Comparator interface.
3430

3531
import java.util.*;
@@ -63,15 +59,12 @@ public class LambdaDemo {
6359
}
6460
}
6561

66-
✅ Output:
67-
62+
Output:
6863
[Bob (25), Alice (30), Charlie (35)]
6964

70-
✅ 3. Chaining Predicates
71-
65+
3. Chaining Predicates
7266
Use multiple conditions with and(), or(), and negate().
7367

74-
7568
import java.util.function.*;
7669

7770
public class LambdaDemo {
@@ -86,15 +79,12 @@ public class LambdaDemo {
8679
System.out.println(isEvenAndPositive.test(-4)); // false
8780
}
8881
}
89-
```
90-
91-
✅ Output:
9282

83+
Output:
9384
true
9485
false
9586

96-
✅ 4. Function Chaining
97-
87+
4. Function Chaining
9888
Chain transformations using andThen() and compose().
9989

10090
import java.util.function.*;
@@ -111,16 +101,13 @@ public class LambdaDemo {
111101
}
112102
}
113103

114-
115-
✅ Output:
116-
104+
Output:
117105
18
118106

119-
5. Handling Exceptions in Lambda
107+
5. Handling Exceptions in Lambda
120108

121109
Use try-catch inside lambdas for error handling.
122110

123-
124111
import java.util.function.*;
125112

126113
public class LambdaDemo {
@@ -138,12 +125,11 @@ public class LambdaDemo {
138125
}
139126
}
140127

141-
✅ Output:
142-
128+
Output:
143129
42
144130
0
145131

146-
6. Parallel Streams with Lambda
132+
6. Parallel Streams with Lambda
147133

148134
Use parallel streams for faster execution on large datasets.
149135

@@ -160,17 +146,15 @@ public class LambdaDemo {
160146
}
161147
}
162148

163-
✅ Output: (Order may vary)
164-
149+
Output: (Order may vary)
165150
2
166151
4
167152
6
168153
8
169154
10
170155
12
171156

172-
✅ 7. Custom Functional Interface
173-
157+
7. Custom Functional Interface
174158
You can define your own functional interface.
175159

176160
@FunctionalInterface
@@ -186,12 +170,10 @@ public class LambdaDemo {
186170
}
187171

188172

189-
✅ Output:
190-
173+
Output:
191174
Sum: 12
192175

193-
✅ 8. Stream.collect() for Grouping Data
194-
176+
8. Stream.collect() for Grouping Data
195177
Group elements using Collectors.groupingBy().
196178

197179
import java.util.*;
@@ -223,12 +205,10 @@ public class LambdaDemo {
223205
}
224206
}
225207

226-
✅ Output:
227-
208+
Output:
228209
{NY=[Alice, Charlie], LA=[Bob]}
229210

230-
✅ 9. Use Lambdas with Optional
231-
211+
9. Use Lambdas with Optional
232212
Handle null values safely with Optional.
233213

234214
import java.util.Optional;
@@ -245,11 +225,10 @@ public class LambdaDemo {
245225
}
246226
}
247227

248-
✅ Output:
249-
228+
Output:
250229
Name not found
251230

252-
10. Combining Streams and Lambdas
231+
10. Combining Streams and Lambdas
253232

254233
Example of map, filter, and reduce together:
255234

@@ -269,15 +248,13 @@ public class LambdaDemo {
269248
}
270249
}
271250

272-
✅ Output:
273-
251+
Output:
274252
Result: 24
275253

276-
🎯 Quick Recap:
277-
254+
Quick Recap:
278255
1. Chain operations with andThen() and compose().
279256
2. Handle exceptions using try-catch inside lambdas.
280257
3. Parallel streams improve performance.
281258
4. Create custom functional interfaces using @FunctionalInterface.
282259
5. Group data** with Collectors.groupingBy().
283-
6. Use Optional to avoid NullPointerException.
260+
6. Use Optional to avoid NullPointerException.

0 commit comments

Comments
 (0)