Stream Operations
Stream Operations
Streams in Java:
Java Streams provide a functional approach to process collections.
They consist of a pipeline of operations to transform data.
Operations on streams are divided into intermediate and terminal operations.
Intermediate operations transform the stream without consuming it.
Terminal operations produce a result or side effect and consume the stream.
Below is an example demonstrating both types of operations.
Example Code:
import java.util.*;
import java.util.stream.*;
// Intermediate Operations
Stream<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J")) // Filtering names starting with 'J'
.map(String::toUpperCase); // Converting to uppercase
// Terminal Operation
filteredNames.forEach(System.out::println); // Printing final results
}
}
Explanation:
1. names.stream() creates a stream from the List.
2. filter() is an intermediate operation that selects names starting with 'J'.
3. map() is an intermediate operation that converts names to uppercase.
4. Intermediate operations return a new stream but do not execute immediately.
5. forEach() is a terminal operation that processes and prints the elements.
6. Once a terminal operation is used, the stream cannot be reused.
7. Streams make code concise, readable, and efficient for bulk data processing.