Streams
Streams
Key Concepts:
Programs can read data from an input stream one item at a time.
Programs can write data to an output stream similarly.
3. Chaining Streams
The output stream of one program can serve as the input stream of another.
Streams are an update to the Java API that allow you to manipulate collections of data in a declarative
way. Instead of coding an ad hoc implementation, you express a query to process the data efficiently.
Java 7 Approach
In Java 7, filtering, sorting, and mapping a list required explicit loops and anonymous classes.
Dish Class
Page 1 of 8
public class Dish {
private String name;
private int calories;
import java.util.*;
Page 2 of 8
}
}
Java 8 introduced the Stream API, which simplifies filtering, sorting, and mapping operations.
1. Declarative approach – No need for explicit loops. Specify what you want to acheive as oppsed
to implement an operation(using for loop and if blocks).
2. Improved readability – Code is more concise and expressive.
3. Better performance – Streams can be parallelized easily.
4. Reusable and composable – Functional-style operations allow easy modifications.
Page 3 of 8
Key Differences:
Real-World Example:
Definition:
External iteration is when the programmer explicitly controls how data is iterated, typically using loops
or iterators.
Page 4 of 8
names.add(dish.getName());
}
Definition:
Internal iteration delegates iteration logic to the Stream API, making code more declarative and
concise.
Page 5 of 8
Concise & Readable: No need for explicit loops.
Optimized Execution: Java handles iteration efficiently.
Easier Parallel Processing: Just use .parallelStream() .
The Stream interface in java.util.stream defines many operations, classified into two
categories:
Intermediate Operations: These return another stream and allow method chaining.
Terminal Operations: These produce a final result or side effect and close the stream.
Intermediate Operations
Intermediate operations return another stream and are lazy, meaning they are not executed until a
terminal operation is invoked.
Page 6 of 8
})
.limit(3)
.collect(toList());
Output:
Filtering: pork
Mapping: pork
Filtering: beef
Mapping: beef
Filtering: chicken
Mapping: chicken
[pork, beef, chicken]
Terminal Operations
Terminal operations consume the stream and produce a final result, such as a List , Integer , or
even void .
Example:
Page 7 of 8
Feature Intermediate Operations Terminal Operations
Effect on
Does not terminate the stream Terminates the stream (cannot reuse it)
Stream
Usage Used for data transformation Used to get final results from the stream
Page 8 of 8