00:00

Stream API in Java 8

Last updated: · Standard (Java 8)

The Stream API, added in Java 8 (JEP 107), lets you process collections declaratively: you describe what to do with the data, such as filter, transform and summarise, and the library handles the looping.

This tutorial covers the structure of a stream pipeline, the difference between intermediate and terminal operations, lazy evaluation and primitive streams. For every individual operation, see the dedicated Stream API tutorials on this site.

1. Why Was the Stream API Added?

Processing collections with loops mixes the business rule with bookkeeping: index variables, temporary lists and accumulators. Streams express the same rule as a chain of steps, which is shorter, easier to read and can run in parallel with one method call.

2. Structure of a Stream Pipeline

Pipeline.java
result = source.stream()          // 1. source
        .filter(predicate)          // 2. intermediate operations (lazy)
        .map(function)
        .collect(Collectors.toList()); // 3. terminal operation (runs the pipeline)
PartExamplesReturns
Sourcelist.stream(), Arrays.stream(arr), Stream.of(...)a Stream
Intermediatefilter, map, sorted, distinct, limita new Stream (lazy)
Terminalcollect, forEach, count, reduce, findFirsta result or side effect

3. Practical Examples

Example 1: A complete pipeline

The program finds customers from Pune with orders above 1000, and also computes totals with a primitive DoubleStream.

StreamPipeline.java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamPipeline {
    static class Order {
        final String customer;
        final String city;
        final double amount;

        Order(String customer, String city, double amount) {
            this.customer = customer;
            this.city = city;
            this.amount = amount;
        }
    }

    public static void main(String[] args) {
        List<Order> orders = Arrays.asList(
                new Order("Asha", "Pune", 1200),
                new Order("Ravi", "Delhi", 450),
                new Order("Meera", "Pune", 3000),
                new Order("John", "Kochi", 800),
                new Order("Asha", "Pune", 650));

        // source -> intermediate operations -> terminal operation
        List<String> bigPuneCustomers = orders.stream()
                .filter(o -> o.city.equals("Pune"))     // keep Pune orders
                .filter(o -> o.amount > 1000)           // keep large ones
                .map(o -> o.customer)                   // Order -> String
                .distinct()
                .sorted()
                .collect(Collectors.toList());
        System.out.println("Big Pune customers: " + bigPuneCustomers);

        double total = orders.stream().mapToDouble(o -> o.amount).sum();
        long smallOrders = orders.stream().filter(o -> o.amount < 1000).count();
        System.out.println("Total revenue     : " + total);
        System.out.println("Orders under 1000 : " + smallOrders);
    }
}
Output
Big Pune customers: [Asha, Meera]
Total revenue     : 6100.0
Orders under 1000 : 3

Example 2: Lazy evaluation and short-circuiting

peek shows when each element is actually processed. Building the pipeline does nothing; findFirst pulls elements one by one and stops at the first PDF.

LazyEvaluation.java
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class LazyEvaluation {
    public static void main(String[] args) {
        List<String> files = Arrays.asList("a.txt", "b.pdf", "c.pdf", "d.doc");

        // Nothing runs until a terminal operation is called
        Stream<String> pipeline = files.stream()
                .peek(f -> System.out.println("  checking " + f))
                .filter(f -> f.endsWith(".pdf"));
        System.out.println("Pipeline built, no element processed yet");

        // findFirst() stops as soon as one match is found (short-circuit)
        Optional<String> firstPdf = pipeline.findFirst();
        System.out.println("First PDF: " + firstPdf.get());

        // Primitive streams avoid boxing; IntStream.rangeClosed builds numbers
        int sumOfSquares = IntStream.rangeClosed(1, 5).map(n -> n * n).sum();
        System.out.println("Sum of squares 1..5 = " + sumOfSquares);
    }
}
Output
Pipeline built, no element processed yet
  checking a.txt
  checking b.pdf
First PDF: b.pdf
Sum of squares 1..5 = 55

Only a.txt and b.pdf are checked. The remaining files are never touched, which is why stream pipelines can be efficient even on large sources.

4. How a Stream Processes Elements

Elements flow one by one through the pipeline A list source feeds elements one at a time through filter and map, and the terminal collect operation gathers the results into a new list. Source orders.stream() filter keep Pune orders map order -> customer collect List<String>
Figure 1: Each element passes through all steps before the next one starts. Nothing happens until the terminal operation asks for data.

5. Important Points and Best Practices

  • A stream can be consumed only once; reusing it throws IllegalStateException.
  • Streams do not modify their source; they produce new results.
  • Avoid side effects inside map or filter; use collectors to build results.
  • Use IntStream, LongStream and DoubleStream for numbers to avoid boxing.
  • parallelStream() helps only for large, CPU-heavy, independent work; measure before using it.

6. Summary

  • Streams process data declaratively and were added in Java 8 (JEP 107).
  • A pipeline has a source, zero or more lazy intermediate operations and one terminal operation.
  • Nothing runs until the terminal operation; short-circuit operations stop early.
  • Streams are single-use and do not change their source.

Related Tutorials

7. References