What are Java Stream API and Lambda Expressions?
Java is a powerful programming language widely used in software development. As a part of Java, the Stream API and Lambda expressions make code writing more efficient and readable. In this article, we will explain what Java Stream API and Lambda expressions are, how they work, and illustrate them with examples.
What is Java Stream API?
Java Stream API is a feature that came with Java 8 and is used to create streams over collections. This supports a more functional programming style and makes it easier to process data. The Stream API allows us to easily perform filtering, sorting, and transformation operations on collections.
Using the Stream API
We can perform some operations on a Java collection using the Stream API. The following example demonstrates filtering numbers in a list and calculating their squares.
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.toList();
System.out.println(squares);
}
}
What are Lambda Expressions?
Lambda expressions are a feature that enhances Java's functional programming capabilities. These expressions enable us to create anonymous functions and write shorter, more readable code. Lambda expressions are particularly useful when working with collections.
Usage with Lambda Expressions
In the example below, a filtering operation is performed on a list using lambda expressions. This is a similar practice to filtering the first 3 numbers and calculating their squares as shown in the previous example.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class LambdaExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> filtered = numbers.stream()
.filter(n -> n > 2)
.collect(Collectors.toList());
System.out.println(filtered);
}
}
Conclusion
Java Stream API and Lambda expressions allow Java developers to write more effective and readable code. These features provide great convenience, especially when processing collections. Learning and using these technologies in Java can significantly improve your software development processes.

Yorum Gönder