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.
filterkeeps items that match a condition.mapchanges each item.sortedsorts them.collect,count,sum,forEachfinish 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.
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.
filter and map are lazy: nothing runs until a final step such as collect or count. A stream can be used only once.- 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.groupingBygroups items by a key.
