Java Stream API: Process Data Step by Step
A stream in Java is a sequence of elements that you process with a chain of operations, such as filter(), map() and collect(), instead of writing a loop. The Java Stream API, added in Java 8 in the java.util.stream package, lets you describe what result you want and leaves the looping to Java.
This tutorial starts from zero. You will learn what a stream is, how a stream pipeline runs, the operations you will use every day, and the mistakes to avoid. Every example was compiled and run on Java 25 and also works on Java 17. Streams use lambda expressions, so it helps to know functional interfaces first.
1. What Is a Stream in Java?
Picture a conveyor belt in a fruit-packing unit. Fruit moves along the belt past several stations: the first removes bruised fruit, the next washes it, and the last packs it into boxes. The belt itself stores nothing; it only moves fruit from one station to the next.
A Java stream works the same way. Your data, for example a List, is the pile of fruit. Each operation, such as filter() or map(), is a station. The final step, such as toList(), packs the result. A stream has five important properties:
- It stores no data. A stream reads elements from a source, such as a collection, an array or a file.
- It does not change the source.
filter()produces a new stream; the original list stays exactly as it was. - It is lazy. Intermediate operations wait until a terminal operation asks for a result.
- It can be used only once. After the terminal operation, the stream is finished.
- It can be endless.
Stream.iterate()andStream.generate()can produce values forever, so you stop them withlimit().
java.util.stream is not related to InputStream and OutputStream in java.io. Those read and write bytes; the Stream API processes elements.2. Why Use Streams?
Suppose you want the names of cities with more than five letters, in capitals, in alphabetical order. Here is the same task written with a loop and with a stream:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LoopVsStream {
public static void main(String[] args) {
List<String> cities = List.of("Pune", "Delhi", "Mumbai", "Bengaluru", "Agra", "Chennai");
// Loop: you manage a temporary list and every step yourself
List<String> loopResult = new ArrayList<>();
for (String city : cities) {
if (city.length() > 5) {
loopResult.add(city.toUpperCase());
}
}
Collections.sort(loopResult);
System.out.println("Loop: " + loopResult);
// Stream: you describe the result you want
List<String> streamResult = cities.stream()
.filter(city -> city.length() > 5)
.map(String::toUpperCase)
.sorted()
.toList();
System.out.println("Stream: " + streamResult);
}
}
Loop: [BENGALURU, CHENNAI, MUMBAI] Stream: [BENGALURU, CHENNAI, MUMBAI]
Both versions give the same answer, but the stream version reads like the task itself: keep long names, make them uppercase, sort them, return a list. Streams help you:
- Write less code: no temporary lists or counters to manage.
- Read the intent quickly: each step has a clear name, such as
filterorsorted. - Combine steps freely: adding a step means adding one line to the chain.
- Reuse ready-made tools: grouping, counting, joining and statistics are built in.
A plain loop is still fine for very simple tasks, or when you need break, checked exceptions or index-based logic.
3. How a Stream Pipeline Works
Every stream task is a pipeline made of three parts:
- A source that supplies the elements, for example
expenses.stream(). - Zero or more intermediate operations that transform the elements, for example
filter()andmap(). Each one returns a newStream, which is why you can chain them. - Exactly one terminal operation that produces the result, for example
toList()orcount().
Streams are lazy
Intermediate operations do not run when you call them. They only record the plan. The work starts when the terminal operation runs, and even then Java processes one element at a time through the whole pipeline, stopping as soon as it can. Print statements make this visible:
import java.util.List;
public class LazyPipelineDemo {
public static void main(String[] args) {
List<String> drinks = List.of("tea", "coffee", "juice", "cocoa");
String firstLongName = drinks.stream()
.filter(drink -> {
System.out.println("filter: " + drink);
return drink.length() > 3;
})
.map(drink -> {
System.out.println("map: " + drink);
return drink.toUpperCase();
})
.findFirst()
.orElse("none");
System.out.println("Result: " + firstLongName);
}
}
filter: tea filter: coffee map: coffee Result: COFFEE
findFirst() has its answer, the rest of the list is skipped.Notice that "juice" and "cocoa" never appear in the output. findFirst() only needs one match, so the stream stops after "coffee". This short-circuiting is why streams can work with very large or even endless sources.
4. Creating a Stream
You can build a stream from almost any group of values:
| Source | How to create the stream |
|---|---|
Any collection (List, Set) | list.stream() |
| A few fixed values | Stream.of("a", "b", "c") |
| An array | Arrays.stream(array) |
| A range of numbers | IntStream.range(1, 5) (1 to 4) or IntStream.rangeClosed(1, 5) (1 to 5) |
| A generated sequence | Stream.iterate(1, n -> n * 2).limit(6) |
| A map | map.entrySet().stream() |
| Lines of a text file | Files.lines(path), opened in try-with-resources |
Characters of a String | text.chars() (an IntStream of character codes) |
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class CreatingStreams {
public static void main(String[] args) {
List<String> colors = List.of("red", "green", "blue");
System.out.println("From a list: " + colors.stream().map(String::toUpperCase).toList());
System.out.println("From values: " + Stream.of("north", "south", "east", "west").toList());
int[] marks = {72, 88, 95};
System.out.println("From an array: sum = " + Arrays.stream(marks).sum());
System.out.println("From a range: " + IntStream.rangeClosed(1, 5).boxed().toList());
System.out.println("Generated: " + Stream.iterate(1, n -> n * 2).limit(6).toList());
}
}
From a list: [RED, GREEN, BLUE] From values: [north, south, east, west] From an array: sum = 255 From a range: [1, 2, 3, 4, 5] Generated: [1, 2, 4, 8, 16, 32]
boxed() converts an IntStream of int values into a Stream<Integer>, which is needed before collecting into a List. Primitive streams are covered in section 8.
5. Intermediate Operations
Intermediate operations shape the data. Each returns a new stream, so you can chain as many as you need:
| Operation | What it does | Example |
|---|---|---|
filter(condition) | Keeps only elements that match the condition | filter(n -> n > 0) |
map(function) | Turns each element into a new value | map(String::length) |
flatMap(function) | Turns each element into a stream and joins them into one | flatMap(List::stream) |
distinct() | Removes duplicates, using equals() | distinct() |
sorted() | Sorts in natural order, or with a Comparator | sorted(Comparator.reverseOrder()) |
limit(n) | Keeps only the first n elements | limit(10) |
skip(n) | Drops the first n elements | skip(20) |
peek(action) | Looks at each element without changing it; meant for debugging | peek(System.out::println) |
The example below uses flatMap() to merge three team lists into one list of people, and skip() with limit() to pick the second "page" of four numbers:
import java.util.List;
import java.util.stream.IntStream;
public class IntermediateOpsDemo {
public static void main(String[] args) {
// Three project teams; Ravi works in two of them
List<List<String>> teams = List.of(
List.of("Asha", "Ravi"),
List.of("Meera"),
List.of("Ravi", "John"));
List<String> everyone = teams.stream()
.flatMap(List::stream) // turn the lists into one stream of names
.distinct() // remove the duplicate "Ravi"
.sorted()
.toList();
System.out.println("All members: " + everyone);
List<Integer> page = IntStream.rangeClosed(1, 10)
.skip(3) // skip 1, 2, 3
.limit(4) // keep the next four
.boxed()
.toList();
System.out.println("Page 2: " + page);
}
}
All members: [Asha, John, Meera, Ravi] Page 2: [4, 5, 6, 7]
With map(), three teams would stay three lists. flatMap() opens each list and pours its names into a single stream, so distinct() can then remove the repeated name.
6. Terminal Operations
A terminal operation runs the pipeline and ends it. It returns a value, a collection, an Optional, or nothing:
| Operation | Returns | Use it to |
|---|---|---|
toList() (Java 16+) | Unmodifiable List | Get the results as a list |
collect(collector) | Depends on the collector | Build a map, set, joined string and more |
forEach(action) | Nothing | Do something with each element, such as print it |
count() | long | Count the elements |
reduce(start, operator) | One combined value | Combine all elements, for example add them up |
min(comparator), max(comparator) | Optional | Find the smallest or largest element |
findFirst(), findAny() | Optional | Get one element |
anyMatch(), allMatch(), noneMatch() | boolean | Check a condition |
Operations such as max() and findFirst() return an Optional, because the stream might be empty. Use orElse() or map() on it instead of calling get() blindly.
7. Complete Example: Monthly Expense Report
Here is a realistic task that combines everything so far. A household tracks its monthly spending, and the program answers five questions: how much was spent, which expenses were big, how much went to each category, what the single costliest item was, and whether any travel expense crossed Rs 1000.
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class ExpenseReport {
record Expense(String item, String category, int amount) { }
public static void main(String[] args) {
List<Expense> expenses = List.of(
new Expense("Groceries", "Food", 3200),
new Expense("Electricity bill", "Utilities", 1850),
new Expense("Movie tickets", "Entertainment", 900),
new Expense("Restaurant dinner", "Food", 2400),
new Expense("Internet", "Utilities", 999),
new Expense("Cab rides", "Travel", 1350),
new Expense("Concert", "Entertainment", 2500),
new Expense("Snacks", "Food", 450));
// 1. Total spent this month
int total = expenses.stream()
.mapToInt(Expense::amount)
.sum();
System.out.println("Total spent: Rs " + total);
// 2. Big expenses (over Rs 2000), largest first
List<String> bigExpenses = expenses.stream()
.filter(e -> e.amount() > 2000)
.sorted(Comparator.comparingInt(Expense::amount).reversed())
.map(Expense::item)
.toList();
System.out.println("Big expenses: " + bigExpenses);
// 3. Total per category, in alphabetical order
Map<String, Integer> byCategory = expenses.stream()
.collect(Collectors.groupingBy(
Expense::category,
TreeMap::new,
Collectors.summingInt(Expense::amount)));
System.out.println("By category:");
byCategory.forEach((category, sum) ->
System.out.printf(" %-14s Rs %d%n", category, sum));
// 4. The single most expensive item
String costliest = expenses.stream()
.max(Comparator.comparingInt(Expense::amount))
.map(Expense::item)
.orElse("none");
System.out.println("Costliest item: " + costliest);
// 5. Did any travel expense cross Rs 1000?
boolean costlyTravel = expenses.stream()
.anyMatch(e -> e.category().equals("Travel") && e.amount() > 1000);
System.out.println("Travel over Rs 1000? " + costlyTravel);
}
}
Total spent: Rs 13649 Big expenses: [Groceries, Concert, Restaurant dinner] By category: Entertainment Rs 3400 Food Rs 6050 Travel Rs 1350 Utilities Rs 2849 Costliest item: Groceries Travel over Rs 1000? true
How the code works
Expenseis arecord(Java 16+), soamount(),item()andcategory()are generated for you.- Total:
mapToInt()turns each expense into itsintamount, andsum()adds them up. - Big expenses:
filter()keeps amounts over 2000,sorted()with a reversed comparator puts the largest first, andmap()keeps only the item name. - By category:
groupingBy()puts each expense into a bucket by category;TreeMap::newkeeps the categories in alphabetical order, andsummingInt()adds the amounts in each bucket. - Costliest item:
max()returns anOptional<Expense>;map()andorElse()read the name safely. - Travel check:
anyMatch()stops at the first expense that matches, so it does not read the whole list when it does not have to.
Each question starts a new stream from expenses. That is normal: streams are cheap to create, and a used stream cannot be reused.
8. Primitive Streams: IntStream, LongStream and DoubleStream
A Stream<Integer> stores every number as an Integer object. For number crunching, Java offers three special streams that work directly with primitive values: IntStream, LongStream and DoubleStream. They avoid the cost of boxing and add handy methods such as sum(), average() and summaryStatistics().
- Convert an object stream with
mapToInt(),mapToLong()ormapToDouble(). - Convert back with
boxed()ormapToObj().
The example below summarizes a week of step counts from a fitness tracker:
import java.util.Arrays;
import java.util.IntSummaryStatistics;
public class StepCounter {
public static void main(String[] args) {
int[] dailySteps = {6200, 8450, 10120, 7300, 9800, 12050, 5400};
IntSummaryStatistics week = Arrays.stream(dailySteps).summaryStatistics();
System.out.println("Days tracked: " + week.getCount());
System.out.println("Total steps: " + week.getSum());
System.out.println("Best day: " + week.getMax());
System.out.println("Lowest day: " + week.getMin());
System.out.printf("Daily average: %.1f%n", week.getAverage());
long activeDays = Arrays.stream(dailySteps)
.filter(steps -> steps >= 8000)
.count();
System.out.println("Days with 8000+ steps: " + activeDays);
}
}
Days tracked: 7 Total steps: 59320 Best day: 12050 Lowest day: 5400 Daily average: 8474.3 Days with 8000+ steps: 4
summaryStatistics() walks the data once and gathers the count, sum, minimum, maximum and average together, which is simpler and faster than five separate streams.
9. Collecting Results with Collectors
The collect() operation takes a collector, a recipe for building the final result. The Collectors class provides the common recipes:
| Collector | Result |
|---|---|
Collectors.toList(), toSet() | A List or Set of the elements |
Collectors.joining(", ") | One String with a separator, plus optional prefix and suffix |
Collectors.groupingBy(key) | A Map from each key to the elements with that key |
Collectors.partitioningBy(condition) | A Map<Boolean, List> with exactly two groups |
Collectors.counting(), summingInt(), averagingDouble() | A count, total or average, often used inside groupingBy() |
Collectors.toMap(key, value) | A Map built from two functions |
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class CollectorsDemo {
public static void main(String[] args) {
List<String> languages = List.of("Java", "Kotlin", "Go", "Python", "Rust", "Scala", "C");
// Join matching values into one String
String shortNames = languages.stream()
.filter(name -> name.length() <= 4)
.collect(Collectors.joining(", ", "[", "]"));
System.out.println("Short names: " + shortNames);
// Split into two groups: true and false
Map<Boolean, List<String>> longOrShort = languages.stream()
.collect(Collectors.partitioningBy(name -> name.length() > 4));
System.out.println("Longer than 4 letters? " + longOrShort);
// Group by any key, here the name length
Map<Integer, List<String>> byLength = languages.stream()
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
System.out.println("By length: " + byLength);
// Count items in each group
Map<Integer, Long> countByLength = languages.stream()
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
System.out.println("Count by length: " + countByLength);
}
}
Short names: [Java, Go, Rust, C]
Longer than 4 letters? {false=[Java, Go, Rust, C], true=[Kotlin, Python, Scala]}
By length: {1=[C], 2=[Go], 4=[Java, Rust], 5=[Scala], 6=[Kotlin, Python]}
Count by length: {1=1, 2=1, 4=2, 5=1, 6=2}
groupingBy() accepts an optional second collector that decides what to keep for each group: toList() keeps the elements, while counting() keeps only how many there are. Passing TreeMap::new sorts the keys; the default HashMap does not guarantee any order.
Collectors.toMap() throws IllegalStateException if two elements produce the same key. Pass a third argument, a merge function such as (first, second) -> first, to decide which value to keep.10. Parallel Streams
Calling parallelStream() on a collection, or parallel() on a stream, splits the work across several CPU cores. By default, the work runs on the shared ForkJoinPool common pool.
long bigOrders = orders.parallelStream()
.filter(order -> order.total() > 10_000)
.count();
Parallel does not automatically mean faster. Splitting the data and combining the results has a cost. A parallel stream usually helps only when:
- the data set is large, often many thousands of elements or more;
- the work for each element is CPU-heavy, not waiting on a database or network;
- the operations are independent and do not change shared variables;
- the order of processing does not matter.
Start with a sequential stream and switch to parallel only after measuring a real improvement.
11. Stream vs Collection
| Aspect | Collection | Stream |
|---|---|---|
| Purpose | Stores and manages data | Processes data |
| Holds elements? | Yes, in memory | No, reads them from a source |
| Changes the data? | Yes: add(), remove() | No, produces new results |
| When values are computed | Before they are added (eager) | Only when the terminal operation asks (lazy) |
| Can be read again? | Yes, as often as needed | No, once only |
| Size | Always finite | Can be infinite, with limit() |
| Iteration | External: you write the loop | Internal: the stream loops for you |
For more on the data structures that streams usually start from, see the Collection Framework.
12. Common Mistakes and Best Practices
Reusing a stream
A stream is consumed by its terminal operation. Using it again fails at runtime:
import java.util.stream.Stream;
public class StreamReuseMistake {
public static void main(String[] args) {
Stream<String> fruits = Stream.of("apple", "banana", "cherry");
System.out.println("Count: " + fruits.count()); // first terminal operation: fine
try {
System.out.println("Count again: " + fruits.count()); // same stream again
} catch (IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Count: 3 Error: stream has already been operated upon or closed
Create a fresh stream from the source each time you need one.
Other mistakes to avoid
- Forgetting the terminal operation. A chain such as
list.stream().filter(...).map(...)with no terminal operation does nothing at all. - Changing shared variables inside a lambda. Adding to an outside list from
forEach()ormap()is error-prone, and breaks with parallel streams. Return the result withtoList()orcollect()instead. - Modifying the source while streaming. Adding to or removing from the source list during the pipeline can throw
ConcurrentModificationException. - Expecting
toList()to be changeable. Its list is unmodifiable, soadd()throwsUnsupportedOperationException. Usecollect(Collectors.toCollection(ArrayList::new))when you need to edit the result. - Calling
Optional.get()without a check. PreferorElse(),orElseThrow()orifPresent(). - Writing one giant chain. If a pipeline grows past a handful of steps, move parts into well-named methods so it stays easy to read.
- Using
peek()for real work. It is meant for debugging; Java may skip it when it can compute the result another way.
13. Summary
- A stream processes elements from a source without storing them and without changing the source.
- A pipeline has a source, zero or more lazy intermediate operations, and exactly one terminal operation that runs everything.
- Use
filter(),map(),flatMap(),sorted(),distinct(),limit()andskip()to shape data. - Finish with
toList(),collect(),count(),reduce(),max()or aMatchmethod. - Use
IntStream,LongStreamandDoubleStreamfor number work, andCollectorsfor grouping, joining and counting. - A stream can be used only once, and parallel streams pay off only for large, CPU-heavy, independent work.
14. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between a Stream and a Collection in Java?
A Collection, such as a List or Set, stores elements in memory and lets you add, remove and read them as often as you like. A Stream stores nothing: it carries elements from a source through a pipeline of operations, computes values on demand and can be used only once. Use a collection to hold data and a stream to process it.
Q2. What is the difference between intermediate and terminal operations?
Intermediate operations such as filter(), map() and sorted() return a new Stream and are lazy, so they only describe work. A terminal operation such as toList(), count(), forEach() or collect() returns a result or causes a side effect, and calling it is what actually runs the whole pipeline. A pipeline can have many intermediate operations but only one terminal operation.
Q3. Can a Java stream be reused?
No. Once a terminal operation has run, the stream is consumed, and calling another operation on it throws IllegalStateException with the message "stream has already been operated upon or closed". If you need the data again, create a new stream from the source, for example by calling list.stream() again, or use a Supplier<Stream<T>> that builds a fresh stream each time.
Q4. What is the difference between map() and flatMap()?
map() turns each element into exactly one new element, so a stream of five orders becomes a stream of five totals. flatMap() turns each element into a stream of zero or more elements and joins all those streams into one, so a stream of three teams becomes a single stream of every team member. Use flatMap() when each element contains a collection you want to work with directly.
Q5. What is the difference between toList() and collect(Collectors.toList())?
Stream.toList(), added in Java 16, returns an unmodifiable List, so calling add() or remove() on it throws UnsupportedOperationException. collect(Collectors.toList()) makes no promise about the type or mutability of the list it returns; in current JDKs it is an ArrayList that you can change. Use toList() when you only read the result, and Collectors.toCollection(ArrayList::new) when you must modify it.
Q6. When should I use a parallel stream?
Use a parallel stream only when the data set is large, the work for each element is CPU-heavy and independent, and the operations do not share mutable state or depend on order. For small lists, I/O-bound work or code that updates shared variables, a parallel stream is usually slower or incorrect. Measure both versions before switching.