?? 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
.NET Developer | C# | TDD | Angular | Azure | SQL
5 个月Excellent content Rodrigo Tenório
Data Engineer | Azure/AWS | Python & SQL Specialist | ETL & Data Pipeline Expert
5 个月Great post!
Senior Java Software Engineer | Spring | Quarkus | Docker | Kubernetes | CI/CD
5 个月Great content, I saved as guide. Thanks