Commit 5315371
committed
feat(functional-interfaces): demonstrate Function, Predicate, Consumer, and Supplier usage
What
- Added FunctionalInterfaceExample class showcasing four core functional interfaces from `java.util.function`:
1. Function<T,R> → transforms input to output.
- Example: String → Integer (length).
2. Predicate<T> → evaluates condition, returns boolean.
- Example: check if an integer is even.
3. Consumer<T> → consumes input, no return.
- Example: prints a message.
4. Supplier<T> → supplies a value without input.
- Example: generates random numbers.
Why
- Functional interfaces are the foundation of Java 8’s functional programming.
- Provides concrete examples for commonly used built-in interfaces.
- Clarifies how lambdas map directly to single abstract methods.
Logic
1. Function<String,Integer> stringLength = str -> str.length();
- Calls `apply("Java8")`, prints length = 5.
2. Predicate<Integer> isEven = n -> n % 2 == 0;
- Tests with 10 (true) and 7 (false).
3. Consumer<String> printMessage = msg -> System.out.println(msg);
- Accepts and prints a custom string.
4. Supplier<Double> randomSupplier = () -> Math.random();
- Generates and supplies a random double value.
Real-life applications
- Function<T,R>: data transformation (DTO mapping, stream map operations).
- Predicate<T>: filtering collections (stream filters, input validation).
- Consumer<T>: logging, notifications, UI rendering actions.
- Supplier<T>: lazy initialization, providing IDs, timestamps, or random values.
Notes
- Each of these interfaces has exactly one abstract method, making them functional interfaces.
- Can be composed or combined with methods like `andThen`, `or`, `negate` for more complex logic.
- Central to Java Streams API and event-driven programming.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d85c515 commit 5315371
File tree
1 file changed
+47
-0
lines changed- Java 8 Crash Course/Functional Interface/src
1 file changed
+47
-0
lines changedLines changed: 47 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 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
0 commit comments