Java Stream API

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 171 of 306

What a Stream Is

A stream (java.util.stream.Stream<T>) is a sequence of elements that you process with a chain of operations — filter these, transform those, sort, take the first three, add them up. Streams arrived in Java 8 together with lambdas, and they changed how most Java code that processes collections is written.

A stream is not a collection. It doesn't store elements; it describes a computation over elements that come from a source — a collection, an array, a file, a generator. The key properties:

PropertyMeaning
No storageElements flow through the pipeline from the source; the stream doesn't hold them
Doesn't modify the sourceFiltering a stream of a list doesn't remove anything from the list
LazyNothing happens until a terminal operation asks for a result
Single useA stream can be traversed only once
Possibly infiniteA stream can produce elements without end, as long as something limits how many are used
DeclarativeYou describe what result you want; the library decides how to loop

Loops versus Streams

Task: from a list of scores, take the three highest passing scores (50 or more) and label them.

import java.util.*;

public class First {
    public static void main(String[] args) {
        List<Integer> scores = List.of(91, 45, 78, 62, 39, 88, 70);

        List<String> loop = new ArrayList<>();
        List<Integer> sorted = new ArrayList<>(scores);
        Collections.sort(sorted, Collections.reverseOrder());
        for (int s : sorted) {
            if (s >= 50) {
                loop.add("PASS " + s);
                if (loop.size() == 3) break;
            }
        }
        System.out.println("loop:   " + loop);

        List<String> stream = scores.stream()
            .filter(s -> s >= 50)
            .sorted(Comparator.reverseOrder())
            .limit(3)
            .map(s -> "PASS " + s)
            .toList();
        System.out.println("stream: " + stream);
        System.out.println("source unchanged: " + scores);
    }
}

Output:

loop:   [PASS 91, PASS 88, PASS 78]
stream: [PASS 91, PASS 88, PASS 78]
source unchanged: [91, 45, 78, 62, 39, 88, 70]

The loop mixes several concerns — copying the list (so the original isn't changed), sorting, filtering, counting and stopping — into one block of control flow, and the reader has to trace the variables to understand the goal.

The stream states each step in order: keep passing scores, sort highest first, take three, label them. Each step is one line, and the source list is untouched. This style is called internal iteration: the stream library runs the loop, and your code supplies only the behaviour for each step (as lambdas).

The Structure of a Pipeline

Every stream pipeline has three parts:

source            →   intermediate operations   →   terminal operation
scores.stream()       .filter(...)                  .toList()
                      .sorted(...)
                      .limit(3)
                      .map(...)
PartWhat it isExamples
SourceWhere the elements come fromlist.stream(), Arrays.stream(array), Stream.of(...), Files.lines(path), IntStream.range(0, 10)
Intermediate operationsTransform a stream into another stream; lazy, return a Streamfilter, map, flatMap, distinct, sorted, limit, skip, peek, takeWhile, dropWhile
Terminal operationProduces a result or a side effect and ends the streamtoList, collect, forEach, count, sum, reduce, min, max, findFirst, anyMatch, allMatch, toArray

A pipeline can have any number of intermediate operations, but exactly one terminal operation at the end. The next lessons cover each group: Stream Creation (sources), Stream Filter and Stream Map (the main intermediate operations), Stream Sort, and Stream Reduce, Stream Collect and Collectors Class (terminal operations).

Lazy Evaluation

Intermediate operations don't do any work when they're called; they only describe the pipeline. Work starts when a terminal operation requests results — and then only as much work as that result needs is done.

import java.util.*;
import java.util.stream.*;

public class Lazy {
    public static void main(String[] args) {
        Stream<String> pipeline = Stream.of("pen", "notebook", "ink", "backpack", "bag")
            .filter(s -> { System.out.println("  filter " + s); return s.length() > 3; })
            .map(s -> { System.out.println("  map    " + s); return s.toUpperCase(); });
        System.out.println("pipeline built, nothing has run yet");

        Optional<String> first = pipeline.findFirst();
        System.out.println("result: " + first.orElse("-"));
    }
}

Output:

pipeline built, nothing has run yet
  filter pen
  filter notebook
  map    notebook
result: NOTEBOOK

Three things to notice:

  1. Nothing runs until findFirst() is called — the first message appears before any filter output.
  2. Elements flow through the pipeline one at a time, not stage by stage. pen is filtered (and rejected); notebook is filtered and then immediately mapped. The stream doesn't first filter all five elements and then map the survivors.
  3. Short-circuiting: once findFirst has a result, processing stops. ink, backpack and bag are never examined.

That's why streams can be efficient even with long pipelines: the work is fused into a single pass, and short-circuiting operations (findFirst, findAny, anyMatch, allMatch, noneMatch, limit) avoid unnecessary work.

Laziness makes infinite streams possible

import java.util.stream.*;

public class Infinite {
    public static void main(String[] args) {
        System.out.println(Stream.iterate(1, n -> n * 2).limit(10).toList());
        System.out.println(IntStream.iterate(1, n -> n + 1)
            .filter(n -> n % 7 == 0 && n % 5 == 0)
            .findFirst().getAsInt());
    }
}

Output:

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
35

Stream.iterate(1, n -> n * 2) describes the endless sequence 1, 2, 4, 8, ... — it's safe because limit(10) stops it. The second pipeline searches the infinite sequence of positive integers for the first number divisible by both 7 and 5, and stops as soon as it finds 35. Without a limiting or short-circuiting operation, an infinite stream would run forever.

Stateful operations change the flow

Most intermediate operations are stateless: each element is handled independently (filter, map). A few are stateful: they need to see other elements first (sorted, distinct). Sorting can't produce its first element until it has seen all of them:

import java.util.stream.*;

public class Order {
    public static void main(String[] args) {
        Stream.of("c", "a", "b")
            .peek(s -> System.out.println("  before sorted: " + s))
            .sorted()
            .peek(s -> System.out.println("  after sorted:  " + s))
            .forEach(s -> System.out.println("  forEach: " + s));
    }
}

Output:

  before sorted: c
  before sorted: a
  before sorted: b
  after sorted:  a
  forEach: a
  after sorted:  b
  forEach: b
  after sorted:  c
  forEach: c

All elements pass through the first stage and are buffered by sorted; then they continue one by one. peek (which runs an action on each element as it passes) is useful exactly for this kind of debugging. Stateful operations need memory proportional to the stream size and can't be used on infinite streams.

A Stream Can Be Used Only Once

import java.util.stream.*;

public class Once {
    public static void main(String[] args) {
        Stream<String> names = Stream.of("Asha", "Ravi");
        System.out.println(names.count());
        try {
            names.count();
        } catch (IllegalStateException e) {
            System.out.println("IllegalStateException: " + e.getMessage());
        }
    }
}

Output:

2
IllegalStateException: stream has already been operated upon or closed

After a terminal operation, the stream is consumed. A stream is like an iterator, not a collection: to process the data again, create a new stream from the source (list.stream() again). This is also why storing a Stream in a field or variable for later reuse is usually a mistake — store the collection, or a Supplier<Stream<T>>, instead.

Avoid Side Effects in Stream Operations

Lambdas passed to stream operations should compute results from their inputs, not modify outside state. Code that adds to an external list from forEach or map works in simple sequential cases, but it's fragile, and it breaks completely when the stream is made parallel:

import java.util.*;
import java.util.stream.*;

public class Side {
    public static void main(String[] args) {
        List<Integer> numbers = IntStream.rangeClosed(1, 10_000).boxed().toList();

        List<Integer> unsafe = new ArrayList<>();
        numbers.parallelStream().filter(n -> n % 2 == 0).forEach(unsafe::add);

        List<Integer> safe = numbers.parallelStream().filter(n -> n % 2 == 0).toList();
        System.out.println("collected with toList: " + safe.size() + " (expected 5000)");
        System.out.println("added from forEach is unreliable; size this run: " + unsafe.size());
    }
}

Output from one run (the second number varies from run to run, and the forEach version can even throw an exception):

collected with toList: 5000 (expected 5000)
added from forEach is unreliable; size this run: 4987

ArrayList isn't thread-safe, so concurrent add calls from the parallel stream lose elements. Letting the stream build the result with a terminal operation — toList(), collect(...), sum() — is correct in both sequential and parallel streams. The rule: use the result of the terminal operation; don't mutate external state from inside the pipeline. forEach is meant for the final action on each element (printing, sending), not for building collections.

Primitive Streams

Besides Stream<T> there are three specialised streams for primitive values: IntStream, LongStream and DoubleStream. They avoid boxing every number into an object and provide numeric operations that Stream<T> doesn't have:

int total = IntStream.rangeClosed(1, 100).sum();                 // 5050
double avg = sales.stream().mapToDouble(Sale::amount).average()  // OptionalDouble
                  .orElse(0);
IntSummaryStatistics stats = IntStream.of(91, 45, 78).summaryStatistics(); // min, max, average, sum, count

mapToInt, mapToLong and mapToDouble convert a Stream<T> into a primitive stream; boxed() converts back. The Stream Map lesson covers these conversions.

When Streams Fit — and When They Don't

Streams are a good fit for:

  • transforming, filtering, grouping and aggregating collections — the bulk of business data processing;
  • pipelines over files (Files.lines) and other large or generated sources;
  • code that reads as a sequence of steps.

A plain loop is often better when:

  • the logic needs to break out early in complex ways, or modify local variables as it goes;
  • you need checked exceptions from the loop body (lambdas can't throw them easily — see the Functional Interfaces lesson);
  • the operation is a simple for over indices, or performance-critical code where a loop is measurably faster;
  • the stream version would need long, nested lambdas — readability is the main benefit of streams, so a stream that's harder to read than the loop is the wrong choice.

Practical Example: Sales Analytics

Business reporting — totals, averages, groupings, top performers — is where streams are used most. This example answers several questions about a month of course sales, each with a short pipeline.

import java.time.*;
import java.util.*;
import java.util.stream.*;

public class Sales {
    record Sale(String course, String city, double amount, LocalDate date, boolean refunded) { }

    public static void main(String[] args) {
        List<Sale> sales = List.of(
            new Sale("Java", "Chennai", 4999, LocalDate.of(2026, 11, 2), false),
            new Sale("Django", "Madurai", 5999, LocalDate.of(2026, 11, 3), false),
            new Sale("Java", "Coimbatore", 4999, LocalDate.of(2026, 11, 5), true),
            new Sale("Docker", "Chennai", 3999, LocalDate.of(2026, 11, 8), false),
            new Sale("Java", "Chennai", 4499, LocalDate.of(2026, 11, 9), false),
            new Sale("Django", "Chennai", 5999, LocalDate.of(2026, 10, 30), false),
            new Sale("Python", "Salem", 2999, LocalDate.of(2026, 11, 12), false));

        LocalDate from = LocalDate.of(2026, 11, 1);
        List<Sale> november = sales.stream()
            .filter(s -> !s.refunded())
            .filter(s -> !s.date().isBefore(from))
            .toList();

        double revenue = november.stream().mapToDouble(Sale::amount).sum();
        long count = november.stream().count();
        OptionalDouble average = november.stream().mapToDouble(Sale::amount).average();

        Map<String, Double> byCourse = november.stream()
            .collect(Collectors.groupingBy(Sale::course, TreeMap::new, Collectors.summingDouble(Sale::amount)));

        String topCity = november.stream()
            .collect(Collectors.groupingBy(Sale::city, Collectors.counting()))
            .entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey).orElse("-");

        List<String> bigTickets = november.stream()
            .filter(s -> s.amount() >= 5000)
            .map(s -> s.course() + "@" + s.city())
            .distinct()
            .toList();

        System.out.printf("November: %d sales, revenue %.2f, average %.2f%n", count, revenue, average.orElse(0));
        System.out.println("by course: " + byCourse);
        System.out.println("top city:  " + topCity);
        System.out.println("big tickets: " + bigTickets);
    }
}

Output:

November: 5 sales, revenue 22495.00, average 4499.00
by course: {Django=5999.0, Docker=3999.0, Java=9498.0, Python=2999.0}
top city:  Chennai
big tickets: [Django@Madurai]

How each question is answered:

  1. Selecting the data: two filter steps remove refunded sales and sales before November. The result is collected once with toList() and reused, because each stream can only be used once — every later question starts a new stream from this list.
  2. Totals and averages: mapToDouble(Sale::amount) switches to a DoubleStream, which has sum() and average(). average() returns an OptionalDouble, because an empty stream has no average (Optional Class lesson).
  3. Revenue per course: Collectors.groupingBy with a downstream summingDouble collector groups and totals in one step; TreeMap::new sorts the courses (Collectors Class lesson).
  4. Top city: count sales per city, then stream the map's entries and pick the entry with the highest value. Chennai has 2 November sales.
  5. Big tickets: filter, transform into labels, and remove duplicates with distinct. The October Django sale was already excluded.

Each pipeline is a few lines, the source list is never modified, and the steps read in the same order as the question they answer.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Stream API and get answers drawn from it.

Signed-in readers only.