What is a stream?
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · A stream does not change its source
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()); }}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.marksis anArrayListthat could be changed, yetfilterdoes 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
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()); }}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.
- 72 enters:
72 > 60is true, so it reachescount. Count is 1. - 45 enters:
45 > 60is false, sofilterdrops it. Count stays 1. - 88 enters: true, it reaches
count. Count is 2. - 59 enters: false, dropped. Count stays 2.
- 61 enters: true, it reaches
count. The source is empty now, so the answer is 3.
Example 3 · Names of students above 60
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()); }}Above 60: [Aarav, Kabir, Rohan] How many: 3
What this code does
mapchanges each value that reaches it. Here aStudentbecomes its name, so aftermapthe flow is aStream<String>instead of aStream<Student>.Student::nameis an unbound method reference to the record accessor, the same ass -> s.name(). The pipeline reads like the task: students, above 60, their names, as a list.
Example 4 · Mistake: storing count() in an int
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); }}CountTypeDemo.java:6: error: incompatible types: possible lossy conversion from long to int
int above = marks.stream().filter(m -> m > 60).count();
^
1 errorWhat this code does
count()returns along. Java will not squeeze alonginto anintwithout 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, butlongis 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.
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
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); }}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 tofilterand letscount()do the counting. count()returns along, so the result goes into alongvariable. 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