Loops versus streams
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Loops and streams can do the same work; the real question is which one says the task more clearly. Streams win when the task is "keep some, change some, build one result". Loops win when the steps depend on positions, on a running state or on checked exceptions.
Every loop part has a stream step
Running state is a value that changes at every step of a loop, such as a total, a counter or a balance. A stream pipeline usually needs none of your own, because the terminal operation keeps it.
Most data loops are built from the same few parts. Each part has a matching stream step, so translating is mostly a matter of spotting them.
Example 1 · Total fees: loop and stream
import java.util.List;
record Student(String name, int feesPaid) {}
public class TotalFeesDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Aarav", 45000), new Student("Diya", 30000), new Student("Kabir", 45000), new Student("Meera", 15000));
int loopTotal = 0; for (Student s : students) { loopTotal += s.feesPaid(); } System.out.println("Loop total: Rs. " + loopTotal);
int streamTotal = students.stream() .mapToInt(Student::feesPaid) .sum(); System.out.println("Stream total: Rs. " + streamTotal); }}Loop total: Rs. 135000 Stream total: Rs. 135000
What this code does
- The running total
loopTotal += ...becomesmapToInt(...)followed bysum().mapToIntturns each student into anint, giving anIntStreamthat can add its values. - Both give Rs. 135000. The stream version has no variable to initialise and no
+=to get wrong. - Why: both walk the list once, so the cost is the same. The stream is shorter and has no total to reset or forget to update.
Example 2 · Names of toppers: filter and transform both ways
import java.util.ArrayList;import java.util.List;
record Student(String name, int marks) {}
public class ToppersDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Aarav", 92), new Student("Diya", 78), new Student("Kabir", 95), new Student("Meera", 89), new Student("Rohan", 90));
List<String> loopToppers = new ArrayList<>(); for (Student s : students) { if (s.marks() >= 90) { loopToppers.add(s.name()); } }
List<String> streamToppers = students.stream() .filter(s -> s.marks() >= 90) .map(Student::name) .toList();
System.out.println("Loop: " + loopToppers); System.out.println("Stream: " + streamToppers); System.out.println("Same result? " + loopToppers.equals(streamToppers)); }}Loop: [Aarav, Kabir, Rohan] Stream: [Aarav, Kabir, Rohan] Same result? true
What this code does
- The
ifbecamefilter,s.name()becamemap(Student::name), andloopToppers.add(...)becametoList(). Read upwards and you have the way back from stream to loop. - One difference:
toList()returns a list that cannot be changed, while the loop builds anArrayListyou can keep adding to. - Why: the loop is no faster, because both visit each student once. The pipeline reads as one sentence: keep the toppers, take their names.
for (Student s : list)→list.stream();if (test) { ... }→filter(test).- Using a changed value, like
s.name()→map(Student::name). result.add(x)→toList();count++→count();total += x→mapToInt(...).sum().- A counter with
breakat n →limit(n);breakat the first match →findFirst()oranyMatch().
When you rewrite a loop, first name the source it walks over. Turn each if that skips elements into a filter, each computed value into a map, and the thing the loop builds into the terminal operation. To go back, do the same in reverse: the terminal operation becomes the result variable declared before the loop.
mapToInt(Student::fees) turns each element into an int and gives an IntStream, whose sum() adds them. The Primitive & Parallel Streams module covers it.When a loop is still better
Index access. Some tasks care about positions: compare each day with the day before, or print "Day 3". A loop has i and list.get(i - 1) right there. A stream has no index, and faking one turns the pipeline into a loop in disguise.
Example 3 · A loop wins: comparing each day with the day before
import java.util.List;
public class AttendanceRiseDemo { public static void main(String[] args) { List<Integer> present = List.of(40, 42, 38, 45, 45, 50);
for (int i = 1; i < present.size(); i++) { int before = present.get(i - 1); int today = present.get(i); if (today > before) { System.out.println("Day " + (i + 1) + ": " + before + " -> " + today); } } }}Day 2: 40 -> 42 Day 4: 38 -> 45 Day 6: 45 -> 50
What this code does
- Each check needs two neighbours,
i - 1andi, and the output needs the day number. A loop index gives all three directly. - A stream has no index or "previous element". A stream version would loop over index numbers and call
present.get(i - 1)inside lambdas: a loop in disguise and harder to read.
Example 4 · A loop wins: stop when the balance runs out
import java.util.List;
public class WalletDemo { public static void main(String[] args) { int balance = 500; List<Integer> bills = List.of(120, 200, 90, 150, 60);
for (int bill : bills) { if (bill > balance) { System.out.println("Stopped: " + bill + " is more than the balance " + balance); break; } balance -= bill; System.out.println("Paid " + bill + ", balance " + balance); } }}Paid 120, balance 380 Paid 200, balance 180 Paid 90, balance 90 Stopped: 150 is more than the balance 90
What this code does
- Whether a bill can be paid depends on every bill paid before it, through the changing
balance. The loop keeps that state in one variable and leaves withbreak. - Stream lambdas should not change outside variables (Java even forbids changing a local
intfrom a lambda). The 60 bill after the stop is never paid, whichfilteralone cannot express.
Example 5 · A loop wins: checked exceptions in a lambda
import java.util.List;
class InvalidMarksException extends Exception { InvalidMarksException(String message) { super(message); }}
public class CheckedLambdaDemo { static int parseMarks(String text) throws InvalidMarksException { int m = Integer.parseInt(text); if (m < 0 || m > 100) { throw new InvalidMarksException("bad marks: " + text); } return m; }
public static void main(String[] args) throws InvalidMarksException { List<String> entries = List.of("72", "88", "105"); List<Integer> marks = entries.stream() .map(t -> parseMarks(t)) .toList(); System.out.println(marks); }}CheckedLambdaDemo.java:21: error: unreported exception InvalidMarksException; must be caught or declared to be thrown
.map(t -> parseMarks(t))
^
1 errorWhat this code does
maindeclaresthrows InvalidMarksException, but that does not help: the call happens inside the lambda, and theFunctionbehindmapcannot throw checked exceptions.- A loop has no such wall:
for (String t : entries) { marks.add(parseMarks(t)); }compiles, and atry/catcharound it can stop at the bad entry with a clear message.
Complex early exit. "Pay bills in order and stop at the first one the balance cannot cover" depends on a running balance that changes at every step. A loop holds that state in a variable and stops with break. Stream lambdas should not change outside variables, so the stream version gets awkward. Checked exceptions. A checked exception is one the compiler forces you to catch or declare, such as IOException. The lambdas in map and filter implement Function and Predicate, whose methods declare no exceptions, so a lambda cannot let a checked exception escape. The code does not compile. A loop simply catches it or passes it on.
Readability: a short pipeline versus a nested loop
A loop that filters, transforms and stops early piles up nesting: an if inside an if, a counter, a break, a result list declared far above. The reader must hold all of it in mind to see what the loop produces.
Example 6 · Readability: nested ifs and a counter versus a pipeline
import java.util.ArrayList;import java.util.List;
record Order(String id, String city, int amount, boolean delivered) {}
public class ReadabilityDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("A101", "Pune", 650, true), new Order("A102", "Delhi", 900, true), new Order("A103", "Pune", 1200, true), new Order("A104", "Pune", 300, true), new Order("A105", "Pune", 800, false), new Order("A106", "Pune", 2100, true), new Order("A107", "Pune", 990, true));
// loop: nested ifs, a counter and a break List<String> loopIds = new ArrayList<>(); int found = 0; for (Order o : orders) { if (o.delivered()) { if (o.city().equals("Pune")) { if (o.amount() > 500) { loopIds.add(o.id()); found++; if (found == 3) { break; } } } } }
// stream: one step per line List<String> streamIds = orders.stream() .filter(Order::delivered) .filter(o -> o.city().equals("Pune")) .filter(o -> o.amount() > 500) .map(Order::id) .limit(3) .toList();
System.out.println("Loop: " + loopIds); System.out.println("Stream: " + streamIds); }}Loop: [A101, A103, A106] Stream: [A101, A103, A106]
What this code does
- The loop needs three levels of
if, a counter and abreak; the reader must trace them to learn that it finds the first three big Pune deliveries. The pipeline says exactly that, one step per line. limit(3)replaces both the counter and thebreak, and laziness means the stream stops reading after A106, just as the loop does.- Why: both stop early, so the cost is the same. The pipeline wins on readability: there is no counter or
breakto keep right.
The pipeline for the same task is flat. Each line is one step, and the order of the lines is the order of the work. Changing a rule means changing one line. The rule cuts both ways. A pipeline whose lambdas run for ten lines, with if, try and outside variables, is harder to read than the loop it replaced. Keep each step to one short line, move bigger logic into a well-named method, and switch back to a loop when the steps stop being simple. Loops over two lists at once, such as comparing every pair of students, also stay clearer as nested loops.
Are streams faster than loops?
Not usually. A stream builds a few pipeline objects and calls a lambda for each element, so for a small list and a simple task a plain loop is often slightly faster. On a modern JVM the gap is small, and for most programs it is far too small to notice.
What really decides speed is the algorithm: how many steps it takes as the data grows. A stream that does O(n) work beats a loop that does O(n²) work, and the other way round. Laziness does not make a stream faster than a loop with break; it only matches it.
So choose for readability first. When speed truly matters, measure both versions on real data before switching. Parallel streams, which can use several CPU cores, are covered in the Primitive & Parallel Streams module.
Next step
Check your understanding
12 quick questions