for / while
Java has four loop forms: classic for, enhanced for-each, while, and do-while. Modern code uses for-each + streams for most jobs; the classic for survives when you need the index.
for, for-each, while, streams
EXAMPLE
import java.util.*;
import java.util.stream.*;
public class Loops {
public static void main(String[] args) {
var xs = List.of(10, 20, 30, 40, 50);
// 1) Classic for — when you need the index
for (int i = 0; i < xs.size(); i++) {
System.out.println(i + " -> " + xs.get(i));
}
// 2) Enhanced for-each — when you don't
for (var n : xs) System.out.println(n);
// Maps
var ages = Map.of("Ada", 36, "Bo", 28);
for (var e : ages.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
// 3) while + do-while
var n = 0;
while (n < 3) n++;
var queue = new ArrayDeque<>(xs);
while (!queue.isEmpty()) {
var head = queue.poll();
System.out.println(head);
}
// 4) Labelled break / continue (rarely needed)
outer:
for (var a : xs) {
for (var b : xs) {
if (a * b > 1000) break outer;
}
}
// 5) Modern alternative — streams
var total = xs.stream().mapToInt(Integer::intValue).sum();
var evens = xs.stream().filter(x -> x % 2 == 0).toList();
var max = xs.stream().max(Comparator.naturalOrder()).orElseThrow();
// 6) IntStream — index + value WITHOUT autoboxing penalty
IntStream.range(0, xs.size()).forEach(i ->
System.out.println(i + " -> " + xs.get(i)));
IntStream.iterate(1, i -> i + 2)
.limit(5)
.forEach(System.out::println);
}
}
Why it matters
For sums, filters, group-bys — reach for streams; the code is shorter and easier to parallelise. Reach for loops when you need break, side effects, or early-return control flow.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
for (int i = 0; i < 3; i++) System.out.println(i);
int n = 0;
while (n < 3) { System.out.println(n); n++; }
for (String s : new String[]{"a","b"}) System.out.println(s);
Try it Yourself »
Discussion
Loading…