← Learning Hub
Beginner

The Stream API

A stream processes a collection step by step, like an assembly line: filter some items, change them, then collect the result. It does not change the original list.

  • filter keeps items that match a condition.
  • map changes each item.
  • sorted sorts them.
  • collect, count, sum, forEach finish the stream and give a result.

Without streams, filtering and transforming data needs loops, temporary lists and if statements. Streams let you describe the steps in order, like a recipe: take the products, keep those under Rs 1000, get their names, sort them, collect into a list. The code reads almost like that sentence.

A stream pipeline has three parts: a source (list.stream()), zero or more intermediate steps (filter, map, sorted) and one terminal step (collect, count, sum) that produces the result. Streams are widely used in real Java projects and are a favourite topic in interviews.

Example
You can edit this code.

Grouping

Collectors can do more than make lists: group items into a map (groupingBy), count per group, join Strings with commas (joining), or add up values. Grouping answers report-style questions like "orders per city" in a single statement.

Example
You can edit this code.
Steps like filter and map are lazy: nothing runs until a final step such as collect or count. A stream can be used only once.
Key points
  • Streams process collections in steps: source -> filter/map -> collect.
  • They don't change the original collection.
  • Intermediate steps are lazy; a terminal step runs the pipeline.
  • Collectors.groupingBy groups items by a key.

📝 Test yourself

1. Which stream step keeps only items that match a condition?
2. Does a stream change the original list?
3. Fill in the step that changes each item:
names.stream().(String::toUpperCase)