Introduce Java Lambda Expressions and give examples
Java Lambda Expressions, introduced in Java 8, provide a clear and concise way to represent a function interface (an interface with a single abstract method) using an expression. They enable you to treat functionality as a method argument, or to create a concise way to express instances of single-method interfaces (functional interfaces).
The basic syntax of a lambda expression is:
(parameters) -> expression
or
(parameters) -> { statements; }
->
): Separates the parameters from the body.Basic Example: Here’s a simple example of a lambda expression that takes two integers and returns their sum.
// Functional interface
interface MathOperation {
int operation(int a, int b);
}
public class LambdaExample {
public static void main(String[] args) {
// Lambda expression for addition
MathOperation addition = (a, b) -> a + b;
System.out.println("10 + 5 = " + addition.operation(10, 5));
}
}
Using Lambda with Collections: You can use lambda expressions with Java's collection framework, such as filtering a list.
import java.util.Arrays;
import java.util.List;
public class LambdaWithCollections {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Using lambda expression to filter names starting with 'A'
names.stream()
.filter(name -> name.startsWith("A"))
.forEach(name -> System.out.println(name));
}
}
Using Lambda with Runnable:
You can also use lambda expressions to implement functional interfaces like Runnable
.
public class LambdaRunnable {
public static void main(String[] args) {
// Lambda expression for Runnable
Runnable runnable = () -> System.out.println("Running in a thread");
// Starting a new thread
Thread thread = new Thread(runnable);
thread.start();
}
}
Using Lambda with Comparator:
Lambda expressions can simplify the implementation of the Comparator
interface.
import java.util.Arrays;
import java.util.Comparator;
public class LambdaComparator {
public static void main(String[] args) {
String[] names = {"John", "Alice", "Bob", "Charlie"};
// Sorting using lambda expression
Arrays.sort(names, (a, b) -> a.compareTo(b));
// Printing sorted names
for (String name : names) {
System.out.println(name);
}
}
}
Java Lambda Expressions provide a powerful way to write more concise and readable code, especially when working with functional interfaces and collections. They are a key feature of Java 8 and beyond, enabling developers to adopt a more functional programming style.