Streams
Overview
A Stream is a pipeline through which data elements flow, letting you perform operations like filtering, mapping, sorting, and aggregation without writing explicit loops. It was introduced in Java 8 (package java.util.stream).
In simple words:
Stream = Data Source → Intermediate Operations → Terminal Operation
Real-Life Example: Factory Conveyor Belt
| Factory | Stream concept |
|---|---|
| Nothing moves until the packing station is on | Lazy evaluation |
| Bottles pass through stations one by one | Elements flow one at a time |
| A packed batch cannot be run through again | A Stream cannot be reused |
| The original crate of bottles is unchanged | Source collection is not modified |
Stream vs Collection
| Feature | Collection | Stream |
|---|---|---|
| Purpose | Stores data | Processes data |
| Data structure | Yes | No (it is a pipeline) |
| Modifies the source | Yes (add/remove) | No |
| Reusable | Yes | No (one terminal operation, then closed) |
| Evaluation | Eager | Lazy |
| Iteration | External (you write the loop) | Internal (Stream does it) |
| Can be infinite | No | Yes (iterate, generate) |
Stream Pipeline
| Step | Rules |
|---|---|
| Create | From a collection, array, values, builder, or generator |
| Intermediate | Zero or more, return another Stream, lazy, can be chained |
| Terminal | Exactly one, triggers execution, produces the result, closes the Stream |
Example: Without Stream vs With Stream
Count salaries greater than 3000.
List<Integer> salaries = List.of(3000, 4000, 1000, 9000, 1000, 3500);// Without Streamint count = 0;for (int salary : salaries) {if (salary > 3000) {count++;}}System.out.println(count); // 3// With Streamlong total = salaries.stream().filter(salary -> salary > 3000).count();System.out.println(total); // 3
The loop says how to do it. The Stream says what you want. This is the declarative style.
Important Properties
| Property | Meaning |
|---|---|
| Does not store data | It carries elements from a source |
| Does not modify the source | Results go into a new collection or value |
| Lazy | Intermediate operations wait for a terminal operation |
| Single use | Closed after the terminal operation |
| Can be sequential or parallel | stream() or parallelStream() |
Interview Definition
A Java Stream is a lazily evaluated, single-use pipeline of operations that processes elements from a data source in a declarative, functional style without modifying the source.
Next TopicStream Creation