Member-only story
As a software engineer, when I work with collections in Java, I often think about this simple question:
Should I use a Loop here, or a stream?
During code reviews, updating legacy code or any kind of feature development, this question daily comes up in my mind. Both loops and streams are widely used and have their own advantages.
Let’s look at loops and streams from scratch and understand which one fits your situation best.
Understanding Loops in Java:
A loop allows you to run a series of code until the condition is fulfilled.
In Java, there are mainly 4 types of loops.
List<Customer> cust= List.of(
new Customer("",true),
new Customer("",true),
new Customer("",true),
new Customer("",true));
// 1. for loop — when you need the index
for (int i = 0; i < customers.size(); i++) {
System.out.println(i + ": " + customers.get(i).getName());
}
// 2. enhanced for-each loop — the most common, clean and readable
for (Customer customer : customers) {
System.out.println(customer.getName());
}
// 3. while loop — when the number of iterations isn't known upfront
int i = 0;
while (i < customers.size()) {
System.out.println(customers.get(i).getName());
i++;
}
// 4. do-while loop — executes at least once before checking condition
int j = 0;
do {…








