00:00

Java Stream API: Process Data Step by Step

Last updated:

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() and Stream.generate() can produce values forever, so you stop them with limit().
Note: The Stream API in 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:

LoopVsStream.java
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);
    }
}
Output
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 filter or sorted.
  • 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:

  1. A source that supplies the elements, for example expenses.stream().
  2. Zero or more intermediate operations that transform the elements, for example filter() and map(). Each one returns a new Stream, which is why you can chain them.
  3. Exactly one terminal operation that produces the result, for example toList() or count().
Parts of a stream pipeline A stream pipeline has three parts. The source is a List of Expense objects, opened with expenses.stream(). Three intermediate operations follow: filter keeps amounts over 2000, sorted puts the largest first, and map turns each expense into its item name. The terminal operation toList collects the result into a List of String. Intermediate operations are lazy; nothing runs until the terminal operation is called. SOURCE INTERMEDIATE OPERATIONS (LAZY) TERMINAL expenses.stream() filteramount > 2000 sortedlargest first mapexpense → item toListList<String> where data comes from each step returns a new Stream produces the result Nothing runs until the terminal operation is called.
Figure 1: A stream pipeline is a source, any number of lazy intermediate operations, and exactly one terminal operation.

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:

LazyPipelineDemo.java
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);
    }
}
Output
filter: tea
filter: coffee
map:    coffee
Result: COFFEE
How the lazy pipeline processes one element at a time The drinks tea, coffee, juice and cocoa flow through filter, map and findFirst one element at a time. Tea has 3 letters and fails the filter, so it goes no further. Coffee has 6 letters, passes the filter, is mapped to COFFEE and is returned by findFirst, which stops the stream. Juice and cocoa are never processed. FILTER (LENGTH > 3) MAP (UPPERCASE) FINDFIRST 1. tea 3 letters ✗ stops here 2. coffee 6 letters ✓ COFFEE found, stop ✓ 3. juice never processed 4. cocoa never processed
Figure 2: Each element travels through the whole pipeline before the next one starts. Once 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:

SourceHow to create the stream
Any collection (List, Set)list.stream()
A few fixed valuesStream.of("a", "b", "c")
An arrayArrays.stream(array)
A range of numbersIntStream.range(1, 5) (1 to 4) or IntStream.rangeClosed(1, 5) (1 to 5)
A generated sequenceStream.iterate(1, n -> n * 2).limit(6)
A mapmap.entrySet().stream()
Lines of a text fileFiles.lines(path), opened in try-with-resources
Characters of a Stringtext.chars() (an IntStream of character codes)
CreatingStreams.java
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());
    }
}
Output
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:

OperationWhat it doesExample
filter(condition)Keeps only elements that match the conditionfilter(n -> n > 0)
map(function)Turns each element into a new valuemap(String::length)
flatMap(function)Turns each element into a stream and joins them into oneflatMap(List::stream)
distinct()Removes duplicates, using equals()distinct()
sorted()Sorts in natural order, or with a Comparatorsorted(Comparator.reverseOrder())
limit(n)Keeps only the first n elementslimit(10)
skip(n)Drops the first n elementsskip(20)
peek(action)Looks at each element without changing it; meant for debuggingpeek(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:

IntermediateOpsDemo.java
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);
    }
}
Output
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:

OperationReturnsUse it to
toList() (Java 16+)Unmodifiable ListGet the results as a list
collect(collector)Depends on the collectorBuild a map, set, joined string and more
forEach(action)NothingDo something with each element, such as print it
count()longCount the elements
reduce(start, operator)One combined valueCombine all elements, for example add them up
min(comparator), max(comparator)OptionalFind the smallest or largest element
findFirst(), findAny()OptionalGet one element
anyMatch(), allMatch(), noneMatch()booleanCheck 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.

ExpenseReport.java
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);
    }
}
Output
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

  1. Expense is a record (Java 16+), so amount(), item() and category() are generated for you.
  2. Total: mapToInt() turns each expense into its int amount, and sum() adds them up.
  3. Big expenses: filter() keeps amounts over 2000, sorted() with a reversed comparator puts the largest first, and map() keeps only the item name.
  4. By category: groupingBy() puts each expense into a bucket by category; TreeMap::new keeps the categories in alphabetical order, and summingInt() adds the amounts in each bucket.
  5. Costliest item: max() returns an Optional<Expense>; map() and orElse() read the name safely.
  6. 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() or mapToDouble().
  • Convert back with boxed() or mapToObj().

The example below summarizes a week of step counts from a fitness tracker:

StepCounter.java
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);
    }
}
Output
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:

CollectorResult
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
CollectorsDemo.java
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);
    }
}
Output
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.

Watch out: 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.

ParallelSnippet.java
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

AspectCollectionStream
PurposeStores and manages dataProcesses data
Holds elements?Yes, in memoryNo, reads them from a source
Changes the data?Yes: add(), remove()No, produces new results
When values are computedBefore they are added (eager)Only when the terminal operation asks (lazy)
Can be read again?Yes, as often as neededNo, once only
SizeAlways finiteCan be infinite, with limit()
IterationExternal: you write the loopInternal: 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:

StreamReuseMistake.java
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());
        }
    }
}
Output
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() or map() is error-prone, and breaks with parallel streams. Return the result with toList() or collect() 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, so add() throws UnsupportedOperationException. Use collect(Collectors.toCollection(ArrayList::new)) when you need to edit the result.
  • Calling Optional.get() without a check. Prefer orElse(), orElseThrow() or ifPresent().
  • 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() and skip() to shape data.
  • Finish with toList(), collect(), count(), reduce(), max() or a Match method.
  • Use IntStream, LongStream and DoubleStream for number work, and Collectors for 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