Skip to content

Commit e9a5429

Browse files
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 changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package FunctionalProgramming;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
import java.util.function.Predicate;
6+
7+
public class Main2 {
8+
public static void main(String[] args) {
9+
Predicate<Integer> isEven = x -> x % 2 == 0;
10+
List<Integer> numbers = Arrays.asList(1,2,3,5,6,7);
11+
12+
for(Integer i : numbers) {
13+
if(isEven.test(i)) {
14+
isEven.test(i);{
15+
System.out.println(i);
16+
}
17+
}
18+
}
19+
}
20+
}

0 commit comments

Comments
 (0)