Video in progress
What is the Stream API and how does it differ from a regular collection?
A stream is a "pipeline" that stores no data: it takes elements from a source (a list, an array, a file) and runs a chain of operations on them. A collection stores data, while a stream processes it.
📖 Answer
A collection is data in memory: the elements sit inside an ArrayList, and you add and remove them. A stream stores nothing. It looks at the source and does the operations you describe.
List<String> names = List.of("Ali", "Vali", "Aziza", "Bobur");
List<String> result = names.stream()
.filter(n -> n.startsWith("A")) // the ones starting with A
.map(String::toUpperCase)
.toList(); // [ALI, AZIZA]
The main differences:
- a stream doesn't modify its source:
namesstays as it was; - a stream is single-use: once it's finished you can't reuse it;
- operations are lazy: nothing runs until a terminal operation is called;
- the code says "what to do", not "how to loop".
The java.util.stream package came in Java 8, and toList() has existed since Java 16.
Sign up to mark studied questions and save your progress.