?? Exploring Java Functional Interfaces ??

?? Exploring Java Functional Interfaces ??

Functional programming in Java has really elevated the way we write code, thanks to Functional Interfaces introduced in Java 8. For those unfamiliar, a Functional Interface is an interface with a single abstract method (SAM), perfect for using lambda expressions to simplify and enhance readability. ??

Here are some real-world examples:

1. Predicate<T> - Evaluates a condition.

Predicate<String> isLongWord = word -> word.length() > 5; System.out.println(isLongWord.test("Functional")); // Output: true
        

2. Function<T, R> - Transforms data from one type to another.

Function<Integer, String> intToString = num -> "Number: " + num; System.out.println(intToString.apply(10)); // Output: Number: 10        

3. Consumer<T> - Performs an action with no return.

Consumer<String> printUpperCase = s -> System.out.println(s.toUpperCase()); printUpperCase.accept("hello world"); // Output: HELLO WORLD        

4. Supplier<T> - Supplies a value when needed.

Supplier<Double> randomValue = () -> Math.random(); System.out.println(randomValue.get()); // Output: Random double value
        

5. Runnable - From the good old days!

Runnable sayHello = () -> System.out.println("Hello, World!"); new Thread(sayHello).start(); // Output: Hello, World!
        

Java's functional interfaces allow us to express complex logic more concisely and effectively, reducing boilerplate and improving maintainability. Whether you’re dealing with collections, streams, or complex data transformations, functional interfaces + lambdas can greatly simplify your Java code.

Great content, thanks for sharing

回复
Lucas Wolff

.NET Developer | C# | TDD | Angular | Azure | SQL

5 个月

Excellent content Rodrigo Tenório

回复
Vitor Raposo

Data Engineer | Azure/AWS | Python & SQL Specialist | ETL & Data Pipeline Expert

5 个月

Great post!

回复
Carlos Betiol

Senior Java Software Engineer | Spring | Quarkus | Docker | Kubernetes | CI/CD

5 个月

Great content, I saved as guide. Thanks

要查看或添加评论,请登录

Rodrigo Tenório的更多文章

社区洞察

其他会员也浏览了