Implementing Lambda Expressions in Java
Lambda expressions in Java enable functional programming by providing a concise syntax for anonymous methods. The basic structure consists of parameters, an arrow operator (->), and a method body. For instance, a lambda can replace verbose anonymous class implementations when working with collections.
import java.util.Arrays;
import java.util.List;
public class LambdaBasicDemo {
public static void main(String[] args) {
List<String> items = Arrays.asList("Apple", "Banana", "Cherry");
items.forEach(element -> System.out.println("Item: " + element));
}
}
Lambda expressions are designed to work with functional interfaces—interfaces containing exactly one abstract method. The java.util.function package includes common types like Supplier, Predicate, and Function.
import java.util.function.Predicate;
public class FunctionalInterfaceDemo {
public static void main(String[] args) {
Predicate<Integer> isEven = value -> value % 2 == 0;
System.out.println("Is 4 even? " + isEven.test(4));
}
}
When combined with the Stream API, lambda expressions facilitate powerful data processing operations such as filtering, transformation, and aggregation.
import java.util.List;
import java.util.stream.Collectors;
public class StreamProcessingDemo {
public static void main(String[] args) {
List<Integer> values = List.of(10, 15, 20, 25, 30);
List<Integer> result = values.stream()
.filter(x -> x > 15)
.map(x -> x + 5)
.collect(Collectors.toList());
System.out.println("Processed values: " + result);
}
}
Lambda expressions can capture variables from their enclosing scope, provided those variables are effectively final. This closure behavior allows lambdas to use external state immutably.
public class ClosureDemo {
public static void main(String[] args) {
final String prefix = "Result: ";
Calculator multiplier = factor -> System.out.println(prefix + factor * 10);
multiplier.compute(7);
}
interface Calculator {
void compute(int value);
}
}