Skip to lesson

A stream is a flow of values that passes through a chain of steps, one value at a time. You describe the steps, such as "keep marks above 60" and "count them", and Java moves every value through them for you.

A flow of values, not a place to store them

A stream is a sequence of elements that flows through a pipeline of operations, such as filter and map, ending in a result. It does not store data or change its source.

A collection, such as an ArrayList, is a place to store values. It keeps them in memory. You can add, remove and read them as often as you like.

A list stores, a stream flows. An ArrayList keeps marks 72, 45, 88, 59 in memory: they stay and get(2) gives 88. A stream carries values from a source to a result: they pass once, there is no get(2), and the stream is finished at the end.

Example 1 · A stream does not change its source

SourceUnchangedDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class SourceUnchangedDemo {    public static void main(String[] args) {        List<Integer> marks = new ArrayList<>(List.of(72, 45, 88, 59, 61));
        List<Integer> passed = marks.stream()                .filter(m -> m >= 60)                .toList();
        System.out.println("All marks:    " + marks);        System.out.println("Passed marks: " + passed);        System.out.println("Sizes: " + marks.size() + " and " + passed.size());    }}
Output
All marks:    [72, 45, 88, 59, 61]
Passed marks: [72, 88, 61]
Sizes: 5 and 3

What this code does

  • toList() ends the stream and gathers every value that reached the end into a new list. It was added in Java 16, and the list it returns cannot be changed.
  • marks is an ArrayList that could be changed, yet filter does not delete 45 and 59 from it. It only stops them from flowing further, so the source still has all five marks.

Example 2 · Trap: printing a stream does not show its values

PrintStreamDemo.javaJava
import java.util.List;import java.util.stream.Stream;
public class PrintStreamDemo {    public static void main(String[] args) {        List<String> cities = List.of("Pune", "Delhi", "Goa");
        Stream<String> flow = cities.stream();        System.out.println(flow);
        System.out.println(cities.stream().toList());    }}
Sample output
java.util.stream.ReferencePipeline$Head@54bedef2
[Pune, Delhi, Goa]

What this code does

  • A stream holds no values, so its toString() cannot list them. Java prints the class name and a hash code instead; the code after @ differs on your computer.
  • To see the values, end the stream with a step that builds a result, such as toList(), and print that result.

A stream stores nothing. It is a flow of values that starts at a source, such as a list, and moves through steps like parcels on a factory conveyor belt. Each value passes once, gets checked or changed, and moves on. When the flow ends, the stream is finished. Streams live in the package java.util.stream. The main type is Stream<T>, where T is the type of the values flowing through it. Any collection gives you one with list.stream() or set.stream().

  • A list holds values; a stream carries values from a source to a result.
  • A stream never changes its source list. It builds a new result instead.
  • A stream has no index: there is no get(2) on a stream.
  • A stream can be walked through only once; a later lesson in this module shows why.

Say what you want, not how to loop

A for loop tells Java how to do the work: start a counter at 0, read each item, test it, add 1, move to the next. You manage every small step, and each step is a place for a bug, such as <= instead of <.

A stream lets you say what you want: "from these marks, keep the ones above 60, then count them". Java runs the loop for you inside the library. This style is called declarative: you declare the result you want. The loop style is called imperative: you give orders one by one.

Both styles do the same work. The stream version is shorter and reads like the task itself, so a reader can check it at a glance.

A first pipeline: count students above 60

A pipeline is a chain of stream steps. This one counts how many marks in [72, 45, 88, 59, 61] are above 60: marks.stream() opens the flow, .filter(m -> m > 60) keeps the passing values, and .count() counts what reaches the end.

  1. 72 enters: 72 > 60 is true, so it reaches count. Count is 1.
  2. 45 enters: 45 > 60 is false, so filter drops it. Count stays 1.
  3. 88 enters: true, it reaches count. Count is 2.
  4. 59 enters: false, dropped. Count stays 2.
  5. 61 enters: true, it reaches count. The source is empty now, so the answer is 3.

Example 3 · Names of students above 60

PassedNamesDemo.javaJava
import java.util.List;
record Student(String name, int marks) {}
public class PassedNamesDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Aarav", 72),                new Student("Diya", 45),                new Student("Kabir", 88),                new Student("Meera", 59),                new Student("Rohan", 61));
        List<String> names = students.stream()                .filter(s -> s.marks() > 60)                .map(Student::name)                .toList();
        System.out.println("Above 60: " + names);        System.out.println("How many: " + names.size());    }}
Output
Above 60: [Aarav, Kabir, Rohan]
How many: 3

What this code does

  • map changes each value that reaches it. Here a Student becomes its name, so after map the flow is a Stream<String> instead of a Stream<Student>.
  • Student::name is an unbound method reference to the record accessor, the same as s -> s.name(). The pipeline reads like the task: students, above 60, their names, as a list.

Example 4 · Mistake: storing count() in an int

CountTypeDemo.javaJava
import java.util.List;
public class CountTypeDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(72, 45, 88);        int above = marks.stream().filter(m -> m > 60).count();        System.out.println(above);    }}
Sample compiler output
CountTypeDemo.java:6: error: incompatible types: possible lossy conversion from long to int
        int above = marks.stream().filter(m -> m > 60).count();
                                                            ^
1 error

What this code does

  • count() returns a long. Java will not squeeze a long into an int without being told, because a large value would lose digits.
  • Fix it with long above = .... If you are sure the count is small, (int) marks.stream()...count() also compiles, but long is the safe default.

filter takes a Predicate, the true-or-false function from the Functional Interfaces module. A value that gives true moves on; a value that gives false is dropped. count() returns a long, not an int, because a stream can be very long.

Fix the error

Fix the stream result

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

Count the marks above 60.

import java.util.List;
public class CountFix {
public static void main(String[] args) {
List<Integer> marks = List.of(72, 45, 88, 59, 61);
int above = marks.stream().filter(m -> m > 60).count();
System.out.println(above);
}
}

Error

CountFix.java:6: error: incompatible types: possible lossy conversion from long to int
        int above = marks.stream().filter(m -> m > 60).count();

The same task as a loop and as a stream

Both versions give 3. The loop needs a counter variable, a loop header and an if. The stream needs one statement, and every word in it names a part of the task: stream, filter, count.

Example 5 · Count marks above 60: loop and stream

CountAboveSixtyDemo.javaJava
import java.util.List;
public class CountAboveSixtyDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(72, 45, 88, 59, 61);
        // the loop way: you write every step        int loopCount = 0;        for (int m : marks) {            if (m > 60) {                loopCount++;            }        }        System.out.println("Loop count:   " + loopCount);
        // the stream way: you say what you want        long streamCount = marks.stream()                .filter(m -> m > 60)                .count();        System.out.println("Stream count: " + streamCount);    }}
Output
Loop count:   3
Stream count: 3

What this code does

  • The loop keeps its own counter and its own if. The stream hands the same test to filter and lets count() do the counting.
  • count() returns a long, so the result goes into a long variable. Both ways print 3, because 72, 88 and 61 are above 60.
  • Why: both look at each mark once, so the cost is the same. The stream version has no counter to start at 0 or forget to increase.

Streams fit tasks like this one: go through a group of values, keep some, change some, and build one result. Real apps do this all day: count UPI payments above ₹500, list students with low attendance, add up the fees still due. Loops are still useful. Some tasks, such as working with an index or stopping in a complex way, stay clearer as loops. The lesson "Loops versus streams" compares the two in detail.

filter, map and toList appear here as a first look. The Transforming Streams and Terminal Operations modules cover each of them fully.

Next step

Check your understanding

11 quick questions