Java
Lambda Expressions
Simplify code with Lambda expressions.
By EZ4Code Team
lambdafunctional
Code
import java.util.*;
// No parameters
Runnable r = () -> System.out.println("Hello");
// Single parameter
List<String> names = List.of("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
// Method reference
names.forEach(System.out::println);
// Two-parameter sort
List<String> sorted = new ArrayList<>(names);
sorted.sort((a, b) -> a.compareTo(b));
// Functional interface
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
MathOperation add = (a, b) -> a + b;
MathOperation mul = (a, b) -> a * b;Explanation
Lambda expressions simplify the implementation of functional interfaces, making code more concise.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.
File IO
Read and write file operations.