Lambda Expressions in Java 8
Java 8 brought a game-changing feature to the world of programming: lambda expressions. These concise and expressive constructs revolutionized the way we write code, enabling functional programming paradigms within Java. In this blog post, we’ll explore lambda expressions, understand what they are, why they matter, and how they work through practical examples.
1. What are Lambda Expressions?
Lambda expressions are a way to define anonymous (unnamed) functions in Java. It allow us to treat functionality as a method argument or code as data, making code more readable and reducing the need for verbose boilerplate code.
A lambda expression consists of three parts:
- Parameters: Enclosed within parentheses, these are the input parameters for the function.
- Arrow Operator (
->
): Separates parameters from the function body. - Body: Contains the code that implements the function.
//Syntax
(parameters) -> {body}
// Example
(name) -> System.out.println("Hello" + name);
2. Why use Lambda Expressions?
Lambda expressions promote cleaner and more concise code. They are particularly powerful when working with collections, parallel processing, and functional interfaces, enhancing code readability and maintainability.
Let’s have a look on the below example that uses the lambda expression:
Example 1: Sorting a List
List<String> names = Arrays.asList("Ram", "Shyam", "Krishna", "Shiv");
// Using lambda expression to sort names
Collections.sort(names, (a, b) -> a.compareTo(b));
// Simplified version using method reference
names.sort(String::compareTo);
Example 2: Mapping with Streams
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Using lambda expression to double each number
List<Integer> doubled = numbers.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
Example 3: Runnable Interface
// Using lambda expression to create a new thread
Runnable task = () -> {
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
};
new Thread(task).start();
3. Lambda Expressions and Functional Interfaces
Lambda expressions shine when used with functional interfaces, which are interfaces that have exactly one abstract method. The java.util.function
package in Java 8 provides several functional interfaces that can be used with lambda expressions, such as Predicate
, Function
, and Consumer
.
Related Posts:
Summary
Lambda expressions are a powerful tool in Java 8, transforming the way we write code. By enabling functional programming concepts and concise syntax, lambda expressions enhance readability and maintainability.
References
- Lambda Expressions – JavaDoc
- Java 8- How to replace word in a File using Stream
- Java 8 – How to sort Set with stream.sorted()