Commit 3acfa5e
committed
feat(ForEachDemo): add demo of forEach with lambdas, method references, and custom filter
What
- Added ForEachDemo class.
- Created a List<Integer> with values [5,10,50,60,70,80,90].
- Demonstrated three uses of forEach():
- With a lambda expression → prints all elements.
- With a method reference → prints all elements in shorter syntax.
- With a custom static helper method show() → prints only elements > 60.
Why
- Illustrates different syntaxes supported by forEach() in Java 8+.
- Demonstrates the power of method references for cleaner code.
- Shows how to integrate custom filtering logic inside helper methods.
How
- list.forEach(n -> System.out.println(n)):
- Explicit lambda parameter, prints each element.
- list.forEach(System.out::println):
- Method reference, shorter equivalent of the above.
- list.forEach(ForEachDemo::show):
- Calls custom show(int n).
- show() checks if n > 60, then prints.
- Prints sections with headings for clarity.
Logic
- Inputs: fixed list of integers.
- Outputs:
- Prints all values via lambda and method reference.
- Prints only values > 60 via custom method.
- Flow:
1. Populate list.
2. Use forEach with lambda.
3. Use forEach with method reference.
4. Use forEach with custom method.
- Edge cases:
- Empty list → forEach does nothing.
- show() filters values, so threshold logic determines output.
- Complexity: O(n) for traversal.
- Concurrency: not thread-safe for concurrent modifications.
Real-life applications
- Iterating collections in a concise, functional style.
- Method references for logging, printing, or invoking existing utilities.
- Passing custom filter/transform logic into forEach for quick one-off behaviors.
Notes
- forEach() is a terminal operation (traverses entire collection).
- Method references (::) are syntactic sugar for simple lambdas.
- For filtering large datasets, prefer streams with filter() instead of custom show().
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 5ea07ab commit 3acfa5e
File tree
1 file changed
+24
-0
lines changed- Section 25 Collections Frameworks/List Interface/ArrayList/src
1 file changed
+24
-0
lines changedLines changed: 24 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
0 commit comments