Commit e9a5429
committed
feat(FunctionalProgramming): add Main2 demonstrating Predicate with manual loop
What
- Added Main2 class in package FunctionalProgramming.
- Defines Predicate<Integer> isEven to check if a number is divisible by 2.
- Creates list [1,2,3,5,6,7].
- Iterates through list with enhanced for-loop.
- Uses isEven.test(i) inside if-statement and prints even numbers.
Why
- Shows how to apply Predicate without streams, in traditional loop style.
- Demonstrates functional-style condition checks replacing explicit modulus in loop.
- Serves as educational example bridging functional interfaces with imperative iteration.
How
- Declared Predicate<Integer> isEven = x -> x % 2 == 0.
- Declared numbers list.
- Iterated using for-each.
- Checked isEven.test(i) to filter even numbers.
- Printed even numbers (2 and 6).
Logic
- Inputs: list [1,2,3,5,6,7].
- Outputs:
- 2
- 6
- Flow:
1. Define predicate for even check.
2. Loop through list.
3. If number satisfies predicate, print it.
4. Only even numbers pass.
- Edge cases:
- List with no even numbers → prints nothing.
- Null values in list would throw NullPointerException when tested.
- Complexity / performance: O(n) for list traversal.
- Concurrency / thread-safety: Safe for single-threaded loop; Predicate is stateless.
- Error handling: No explicit exceptions; relies on valid non-null inputs.
Real-life applications
- Using Predicate as reusable logic component for validation/filters.
- Encapsulating business rules in predicates that can be reused in multiple contexts.
- Educational example of integrating functional programming into traditional loops.
Notes
- Extra isEven.test(i); statement inside block is redundant; has no effect.
- Same logic can be expressed more concisely with streams: numbers.stream().filter(isEven).forEach(System.out::println).
- Predicates are composable (and/or/negate), allowing complex conditions beyond simple modulus checks.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d6c607a commit e9a5429
File tree
1 file changed
+20
-0
lines changed- Java 8 Crash Course/Predicate/src/FunctionalProgramming
1 file changed
+20
-0
lines changedLines changed: 20 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 | + | |
0 commit comments