Lambda Expression
import java.util.*;
public class LambdaExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Using lambda expression
names.forEach(name -> System.out.println(name));
// Using method reference
names.forEach(System.out::println);
}
}
Functional Interface
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
public class FunctionalInterfaceExample {
public static void main(String[] args) {
MathOperation addition = (a, b) -> a + b;
MathOperation subtraction = (a, b) -> a - b;
System.out.println("10 + 5 = " + operate(10, 5, addition));
System.out.println("10 - 5 = " + operate(10, 5, subtraction));
}
private static int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operate(a, b);
}
}