0% found this document useful (0 votes)
0 views1 page

Stream Operations

Java Streams provide a functional approach to process collections through a pipeline of operations, categorized as intermediate and terminal. Intermediate operations transform the stream without consuming it, while terminal operations produce a result and consume the stream. An example demonstrates filtering names starting with 'J' and converting them to uppercase, followed by printing the results using a terminal operation.

Uploaded by

Rohit Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views1 page

Stream Operations

Java Streams provide a functional approach to process collections through a pipeline of operations, categorized as intermediate and terminal. Intermediate operations transform the stream without consuming it, while terminal operations produce a result and consume the stream. An example demonstrates filtering names starting with 'J' and converting them to uppercase, followed by printing the results using a terminal operation.

Uploaded by

Rohit Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Intermediate and Terminal Operations on Streams

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.*;

public class StreamOperationsExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Emma", "Mike", "David", "Sophia");

// 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.

You might also like