Skip to content

Commit d85c515

Browse files
committed
feat(functional-interfaces): add demo using Function<T,R> to compute string length
What - Introduced FunctionalInterfaceDemo class. - Demonstrates usage of built-in functional interface `Function<T,R>` from `java.util.function`. - Example logic: - Defines a Function<String, Integer> mapping a string to its length. - Applies it to the string "Java 8". - Prints the computed length. Why - Shows practical usage of a functional interface without writing custom ones. - Highlights how lambdas implement single abstract methods cleanly. - Reinforces role of functional interfaces in functional programming style introduced in Java 8. Logic 1. Function<T,R> has one abstract method → `R apply(T t)`. 2. Lambda `str -> str.length()` implements this method, mapping a String input to an Integer output. 3. The function is applied with input `"Java 8"` returning `7`. 4. Demonstrates concise functional programming over traditional anonymous classes. Real-life applications - Transforming data in Streams (`map` operations). - Converting domain objects (e.g., User → UserDTO). - Processing strings (extracting substrings, normalizing cases). - Mapping request data to processed formats in APIs. Notes - Functional interface `Function<T,R>` is parameterized: T = input type, R = return type. - Commonly chained with `andThen` and `compose` for function composition. - Part of core functional interfaces in `java.util.function` alongside Predicate, Consumer, Supplier. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent d79837e commit d85c515

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import java.util.function.Function;
2+
3+
public class FunctionalInterfaceDemo {
4+
public static void main(String[] args) {
5+
// Using Function<T, R> to convert a String to its length.
6+
Function<String, Integer> stringLengthFunction = str -> str.length();
7+
8+
// Applying the function
9+
int length = stringLengthFunction.apply("Java 8");
10+
System.out.println("Length of 'Java 8': " + length);
11+
}
12+
}

0 commit comments

Comments
 (0)