Module 4 · The standard library, in depth Lesson 10 of 15
Streams: loops that say what they mean
A stream turns a loop into a pipeline: filter, map, sort, collect. It removes the index, the temporary list and the off-by-one, and it reads like the sentence describing the job.
The concept
Streams are not automatically faster; their value is clarity. Keep them for short pipelines and go back to a loop when the body grows past a step or two.
filter keeps some elements, map changes each one, collect gathers the result, forEach acts - those four cover most of what an interview asks.
List<String> aNames = names.stream()
.filter(n -> n.startsWith("A"))
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
int total = students.stream()
.filter(s -> s.getMarks() >= 40)
.mapToInt(Student::getMarks)
.sum();Worked example
names.stream().filter(n -> n.startsWith("A")).sorted().collect(Collectors.toList()) keeps the A-names, in order, in one expression.
Your practice task
Rewrite a loop over students as a stream that keeps the passed ones and prints their names, sorted.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
Streams are not automatically faster; their value is clarity.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.