![]() |
VOOZH | about |
Stream in Java was introduced in Java 8 to simplify the processing of collections and data. It provides a modern and efficient way to perform operations on groups of objects using a functional programming approach. Streams help developers write cleaner, shorter, and more readable code for data processing tasks.
Java Stream Creation is one of the most basic steps before considering the functionalities of the Java Stream. Below is the syntax given for declaring a Java Stream.
Stream<T> stream;
Stream<T>: general object stream for reference types
The features of Java streams are mentioned below:
There are two types of Operations in Streams:
Intermediate operations are the operations that transform a stream into another stream. These operations are lazy in nature, meaning they do not execute until a terminal operation is called.
Intermediate Operations are the types of operations in which multiple methods are chained in a row.
There are a few Intermediate Operations mentioned below:
1. map(): The map method is used to return a stream consisting of the results of applying the given function to the elements of this stream.
Syntax:
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
2. filter(): The filter method is used to select elements as per the Predicate passed as an argument.
Syntax:
Stream<T> filter(Predicate<? super T> predicate)
3. sorted(): The sorted method is used to sort the stream.
Syntax:
Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)
4. flatMap(): The flatMap operation in Java Streams is used to flatten a stream of collections into a single stream of elements.
Syntax:
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
5. distinct(): Removes duplicate elements. It returns a stream consisting of the distinct elements (according to Object.equals(Object)).
Syntax:
Stream<T> distinct()
6. peek(): Performs an action on each element without modifying the stream. It returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
Syntax:
Stream<T> peek(Consumer<? super T> action)
Example: Program that demonstrates the use of all the intermediate operations:
Intermediate Results: STRUCTURE STREAM STATE SORTING Final Result: SORTING STATE STREAM STRUCTURE
The program prints the intermediate results stored in the intermediateResults set. Finally, it prints the result list, which contains the fully processed strings after all stream operations.
Terminal operations are the operations that produce the final result from a stream and end the stream processing. These operations trigger the execution of all intermediate operations.
These Operations are not processed further just return a final result value.
1. collect(): The collect method is used to return the result of the intermediate operations performed on the stream.
Syntax:
<R, A> R collect(Collector<? super T, A, R> collector)
2. forEach(): The forEach method is used to iterate through every element of the stream.
Syntax:
void forEach(Consumer<? super T> action)
3. reduce(): The reduce method is used to reduce the elements of a stream to a single value. The reduce method takes a BinaryOperator as a parameter.
Syntax:
T reduce(T identity, BinaryOperator<T> accumulator)
Optional<T> reduce(BinaryOperator<T> accumulator)
4. count(): Returns the count of elements in the stream.
Syntax:
long count()
5. findFirst(): Returns the first element of the stream, if present.
Syntax:
Optional<T> findFirst()
6. allMatch(): Checks if all elements of the stream match a given predicate.
Syntax:
boolean allMatch(Predicate<? super T> predicate)
7. anyMatch(): Checks if any element of the stream matches a given predicate.
Syntax:
boolean anyMatch(Predicate<? super T> predicate)
Here ans variable is assigned 0 as the initial value and i is added to it.
Example: Program Using all Terminal Operations
Output:
Explanation:
The program prints each name, names starting with 'S', concatenated names, the count of names, the first name, whether all names start with 'S' and whether any name starts with 'S'.
Intermediate Operations are running based on the concept of Lazy Evaluation, which ensures that every method returns a fixed value(Terminal operation) before moving to the next method.
Filtering: Aman Filtering: Sita Mapping: Sita First name starting with 'S': SITA
Explanation: Intermediate operations in a stream (like filter and map) are lazy and process elements one by one only when a terminal operation (like findFirst) is invoked, allowing early termination and efficient execution.
There are some benefits because of which we use Stream in Java as mentioned below:
Streams are widely used in modern Java applications for:
| Intermediate Operation | Terminal Operation |
|---|---|
| Returns another stream. | Produces the final result or output. |
| Executes lazily and waits for a terminal operation. | Triggers the execution of the stream pipeline. |
| Used for transforming or filtering data. | Used for collecting, displaying, or reducing data. |
| Multiple intermediate operations can be chained. | Usually appears at the end of the stream. |
Examples: filter(), map(), sorted() | Examples: collect(), forEach(), count() |