📊 We use cookies & analytics to improve your experience. Learn more
Latest

Java Programming Foundations Module 4 · Lesson 10 of 15

0% Exit to course

Module 4 · The standard library, in depth Lesson 10 of 15

Streams: loops that say what they mean

Learning objective

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.

Java
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.

Create free account or sign in

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.

Next recommended course Python for Absolute Beginners