If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, Stream
is a powerful and flexible API introduced in Java 8 as part of the Java Collections Framework. It allows you to perform aggregate operations on collections (or other data sources) in a declarative and functional style. Streams provide a way to express complex data processing tasks more concisely and efficiently compared to traditional iteration-based approaches.
A Stream
is not a data structure by itself but rather a way to process data from a data source, such as a Collection
, an array, or an I/O channel. The data source remains unchanged after the stream operations are performed.
To work with streams, you first obtain a stream from a data source, apply intermediate operations (such as filter
, map
, sorted
, etc.) to transform or filter the data, and then apply terminal operations (such as collect
, reduce
, forEach
, etc.) to produce a result or perform a final action.
Here are some key concepts related to streams:
Collection
, array, or use the Stream.of()
method for individual elements.List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Stream<Integer> stream = numbers.stream();
filter
, map
, sorted
, distinct
, limit
, skip
, etc.collect
, forEach
, reduce
, count
, min
, max
, anyMatch
, allMatch
, noneMatch
, etc.Here's a simple example to demonstrate how streams work:
javaCopy code
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);
// Filter even numbers, map to their squares, and print the result
numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.forEach(System.out::println); // Output: 4 16
}
}
In this example, we have a list of integers numbers
. We use the stream()
method to create a stream from this list. We then use intermediate operations filter
to keep only the even numbers and map
to square each number. Finally, we use the terminal operation forEach
to print the resulting stream.
The output will be:
Copy code
4
16
Streams provide a concise and expressive way to perform complex data processing tasks with improved readability and maintainability. They are particularly useful when dealing with large datasets and enable you to leverage multi-core architectures efficiently.
Comments: 0