Java 8 introduced lambda expressions, which provide a clear and concise way to represent anonymous functions. Lambdas help in reducing boilerplate code, improving readability, and making functional programming more accessible in Java.
What is a Lambda Expression?
A lambda expression is essentially an anonymous function that can be passed as an argument to a method. It has the following syntax:
(parameters) -> expression
or
(parameters) -> { statements; }
Example 1: Using Lambda in a Functional Interface
A functional interface is an interface with a single abstract method. Java 8 introduced the @FunctionalInterface
annotation to enforce this constraint.
@FunctionalInterface
interface MathOperation {
int operation(int a, int b);
}
We can implement this interface using lambda expressions:
public class LambdaExample {
public static void main(String[] args) {
MathOperation addition = (a, b) -> a + b;
MathOperation subtraction = (a, b) -> a - b;
System.out.println("Addition: " + addition.operation(10, 5));
System.out.println("Subtraction: " + subtraction.operation(10, 5));
}
}
Example 2: Using Lambda with Collections
Lambda expressions can simplify operations on collections. Consider sorting a list:
import java.util.*;
public class LambdaSortExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Anna", "Mike", "Sophia");
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
System.out.println(names);
}
}
Example 3: Using Lambda with Streams
Streams API in Java 8 is enhanced by lambda expressions for efficient data processing:
import java.util.*;
import java.util.stream.*;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
}
}
Conclusion
Lambda expressions in Java 8 simplify the syntax and improve the readability of Java code. They are particularly useful in functional interfaces, collections, and stream operations. By leveraging lambdas, developers can write more expressive and concise code.