The Stream API is one of the major additions to Java 8 and provides a powerful way to process collections of objects. It allows you to perform versatile operations such as filtering elements, transforming elements, and reducing elements in a declarative and concise manner.
To work with the Stream API, you first need a data source, typically a collection or an array. Here's an example using an ArrayList
:
1List<Integer> numbers = new ArrayList<>();
2numbers.add(1);
3numbers.add(2);
4numbers.add(3);
5numbers.add(4);
6numbers.add(5);
Once you have a data source, you can create a stream from it using the stream()
method. From there, you can chain multiple operations on the stream to manipulate and process the elements.
Let's explore some common operations provided by the Stream API:
- Filtering: The
filter()
method allows you to filter the elements based on a condition. For example, you can filter even numbers from a list of integers:
1List<Integer> evenNumbers = numbers.stream()
2 .filter(num -> num % 2 == 0)
3 .collect(Collectors.toList());
- Mapping: The
map()
method allows you to transform each element in the stream. For example, you can square each number in the list:
1List<Integer> squaredNumbers = numbers.stream()
2 .map(num -> num * num)
3 .collect(Collectors.toList());
- Reducing: The
reduce()
method allows you to perform a reduction operation on the elements in the stream. For example, you can calculate the sum of the numbers in the list:
1int sum = numbers.stream()
2 .reduce(0, (a, b) -> a + b);
These are just a few examples of what you can do with the Stream API. It provides many more operations like sorting, finding, grouping, and more.
By leveraging the Stream API, you can write more concise and expressive code to process collections in Java.
xxxxxxxxxx
}
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
System.out.println("Original List: " + numbers);
// Stream API - Filter
List<Integer> evenNumbers = numbers.stream()
.filter(num -> num % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even Numbers: " + evenNumbers);
// Stream API - Map
List<Integer> squaredNumbers = numbers.stream()
.map(num -> num * num)
.collect(Collectors.toList());
System.out.println("Squared Numbers: " + squaredNumbers);
// Stream API - Reduce
int sum = numbers.stream()