Lambda expressions in Java are a feature introduced in Java 8 that provides a clear and concise way to represent instances of single-method interfaces (functional interfaces). They are essentially a shorthand for anonymous classes with a single method.
Lambda expressions in Java simplify code by reducing verbosity, improving readability, and enabling more expressive and functional-style programming. They are a powerful feature that enhances the way you write and understand Java code.
Syntax of Lambda Expressions
The syntax of a lambda expression is:
(parameters) -> expression
or
(parameters) -> { statements; }
Simplifying Code with Lambda Expressions
Reducing Boilerplate Code: Before Java 8, implementing an interface with a single method (like
Runnable
or Comparator
) required an anonymous inner class. With lambda expressions, this can be done in a much more concise way.
// Before Java 8
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Hello, World!");
}
};
// With Lambda Expression
Runnable runnable = () -> System.out.println("Hello, World!");
Improving Readability: Lambda expressions make the code more readable and expressive, especially for operations on collections, such as filtering, mapping, and reducing.
// Before Java 8
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> filteredNames = new ArrayList<>();
for (String name : names) {
if (name.startsWith("A")) {
filteredNames.add(name);
}
}
// With Lambda Expression and Streams
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
Enabling Functional Programming: Lambda expressions enable functional programming techniques in Java. They work seamlessly with the new Stream API introduced in Java 8, allowing for more functional-style operations on collections.
// Java program to illustrate the concept
// of Collection objects storage in a HashSet
import java.io.*;
import java.util.*;
class CollectionObjectStorage {
public static void main(String[] args)
{
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * n)
.sum();
System.out.println(sum);
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
}
}
Output:
20
Alice
Bob
Charlie
Read more
What are lambda expressions, and how are they used in LINQ queries?
How to use a lambda expression in Enumerable.Distinct()?
Where and when to use Lambda in coding?
Leave Comment