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

FactoryStream concept
Nothing moves until the packing station is onLazy evaluation
Bottles pass through stations one by oneElements flow one at a time
A packed batch cannot be run through againA Stream cannot be reused
The original crate of bottles is unchangedSource collection is not modified

Stream vs Collection

FeatureCollectionStream
PurposeStores dataProcesses data
Data structureYesNo (it is a pipeline)
Modifies the sourceYes (add/remove)No
ReusableYesNo (one terminal operation, then closed)
EvaluationEagerLazy
IterationExternal (you write the loop)Internal (Stream does it)
Can be infiniteNoYes (iterate, generate)

Stream Pipeline

StepRules
CreateFrom a collection, array, values, builder, or generator
IntermediateZero or more, return another Stream, lazy, can be chained
TerminalExactly 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 Stream
int count = 0;
for (int salary : salaries) {
if (salary > 3000) {
count++;
}
}
System.out.println(count); // 3
// With Stream
long 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

PropertyMeaning
Does not store dataIt carries elements from a source
Does not modify the sourceResults go into a new collection or value
LazyIntermediate operations wait for a terminal operation
Single useClosed after the terminal operation
Can be sequential or parallelstream() 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