forEach and count
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A terminal operation is the last step of a stream pipeline: it runs the pipeline and gives you something back. forEach does an action for every element, and count tells you how many elements reached the end.
Why a stream needs a terminal operation
filter, map and sorted are intermediate operations. They only describe the work, and they are lazy: nothing runs until a terminal operation asks for the result. A pipeline without one does nothing at all.
Example 1 · forEach prints every element
import java.util.List;
public class ForEachDemo { public static void main(String[] args) { List<String> names = List.of("Aarav", "Priya", "Rohan", "Kavya");
// old way: a for-each loop for (String name : names) { System.out.println("Hello, " + name); }
// stream way: forEach with a lambda names.stream() .filter(name -> name.startsWith("R") || name.startsWith("K")) .forEach(name -> System.out.println("Selected: " + name));
// forEach with a method reference names.stream() .map(String::toUpperCase) .forEach(System.out::println); }}Hello, Aarav Hello, Priya Hello, Rohan Hello, Kavya Selected: Rohan Selected: Kavya AARAV PRIYA ROHAN KAVYA
What this code does
forEachtakes aConsumer: a lambda that receives one element and returns nothing. It runs once for every element that reaches the end of the pipeline.System.out::printlnis a bound method reference, the same ass -> System.out.println(s).forEachreturnsvoid, so it is always the last call in the chain.
Before streams, you printed a list with a for-each loop: for (String n : names) System.out.println(n);. The stream way is names.stream().forEach(n -> System.out.println(n));, or with a method reference, forEach(System.out::println). forEach takes a Consumer<T>: a function that receives one value and returns nothing. So forEach itself returns void. Nothing can come after it, and it gives you no result to store.
IllegalStateException.count returns a long
Counting with a loop needs three parts: a counter set to 0, an if, and counter++. With a stream you filter and then call count(): long passed = marks.stream().filter(m -> m >= 40).count();.
Example 2 · count: how many students passed
import java.util.List;
record Student(String name, int marks) {}
public class CountDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Aarav", 72), new Student("Priya", 38), new Student("Rohan", 91), new Student("Kavya", 35), new Student("Divya", 64));
long total = students.stream().count(); long passed = students.stream() .filter(s -> s.marks() >= 40) .count(); long failed = total - passed;
System.out.println("Students: " + total); System.out.println("Passed: " + passed); System.out.println("Failed: " + failed); System.out.println("Pass %: " + (passed * 100 / total));
long checked = students.stream() .peek(s -> System.out.println("checking " + s.name())) .count(); System.out.println("Counted without peek: " + checked); }}Students: 5 Passed: 3 Failed: 2 Pass %: 60 Counted without peek: 5
What this code does
filter(...).count()replaces the counter, theifand the++of a loop. The result is along, so the arithmetic for the pass percentage is done inlongtoo.- The last pipeline prints no "checking" lines. The list already knows its size and nothing changes it, so
count()skips the pipeline andpeeknever runs. Never rely onpeekormapside effects beforecount().
count() returns a long, not an int, because a stream can have more than 2.1 billion elements. Writing int n = stream.count(); does not compile (possible lossy conversion from long to int). Store it in a long, or use Math.toIntExact(n) when you are sure it fits. Since Java 9, count() may skip the pipeline when it can know the size straight from the source. List.of(1, 2, 3).stream().peek(...).count() returns 3 and never runs peek. A filter in between forces the real work, because the size is unknown until each element is tested.
Iterable.forEach, stream().forEach and forEachOrdered
Every List and Set already has a forEach method, from the Iterable interface. names.forEach(System.out::println) prints the list with no stream at all. Map has its own forEach((key, value) -> ...). Use these when you only want to act on every element.
Example 3 · Iterable.forEach, stream().forEach and Map.forEach
import java.util.List;import java.util.Map;import java.util.TreeMap;
public class IterableForEachDemo { public static void main(String[] args) { List<String> subjects = List.of("Maths", "Physics", "Chemistry");
// no stream needed to act on every element subjects.forEach(s -> System.out.println("List: " + s));
// a stream is useful when you filter or map first subjects.stream() .filter(s -> s.length() > 5) .forEach(s -> System.out.println("Stream: " + s));
Map<String, Integer> fees = new TreeMap<>(); fees.put("Tuition", 120000); fees.put("Hostel", 45000); fees.put("Library", 2000); fees.forEach((item, amount) -> System.out.println(item + " = Rs. " + amount)); }}List: Maths List: Physics List: Chemistry Stream: Physics Stream: Chemistry Hostel = Rs. 45000 Library = Rs. 2000 Tuition = Rs. 120000
What this code does
subjects.forEach(...)comes fromIterable, so it works on anyListorSetwithout creating a stream. It always follows the collection's own order.Map.forEachgives the key and the value together, as aBiConsumer. ATreeMapkeeps its keys sorted, so the fee items print A to Z.
Example 4 · forEachOrdered keeps the order in a parallel stream
import java.util.List;
public class OrderedDemo { public static void main(String[] args) { List<Integer> tokens = List.of(101, 102, 103, 104, 105, 106, 107, 108);
System.out.print("forEach: "); tokens.parallelStream().forEach(t -> System.out.print(" " + t)); System.out.println();
System.out.print("forEachOrdered:"); tokens.parallelStream().forEachOrdered(t -> System.out.print(" " + t)); System.out.println(); }}forEach: 106 105 103 108 107 104 102 101 forEachOrdered: 101 102 103 104 105 106 107 108
What this code does
parallelStream()splits the tokens across several threads.forEachprints each token as soon as its thread reaches it, so the first line is in a different order on every run.forEachOrderedwaits so that elements are handled in encounter order, the order of the list. It gives up some of the parallel speed to keep that promise.
Use stream().forEach when you first need filter, map or sorted. The stream version promises nothing about order, though. A parallel stream (from list.parallelStream()) splits the work across several threads, so forEach may print elements in any order. forEachOrdered keeps the encounter order, the order the source gives the elements, even in a parallel stream. Use it when the order of printing matters, such as a numbered token queue.
Trap: building results inside forEach
A side effect is a change a lambda makes outside itself, such as adding to an outside list or changing a field. forEach exists for side effects like printing or sending a message. It is the wrong tool for building a result.
Example 5 · Trap: a counter inside forEach does not compile
import java.util.List;
public class CounterTrapDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 38, 91, 35, 64); int passed = 0; marks.stream().forEach(m -> { if (m >= 40) { passed++; } }); System.out.println("Passed: " + passed); }}CounterTrapDemo.java:9: error: local variables referenced from a lambda expression must be final or effectively final
passed++;
^
1 errorWhat this code does
- A lambda may read a local variable only if the variable never changes after it is set.
passed++changes it, so the compiler rejects the program. - The fix is not a trick like an
int[]box. Let the stream count:long passed = marks.stream().filter(m -> m >= 40).count();.
Example 6 · Trap: adding to an outside list, and the fix
import java.util.ArrayList;import java.util.List;
public class OutsideListDemo { public static void main(String[] args) { List<String> names = List.of("Aarav", "Ishaan", "Priya", "Siddharth", "Kavya");
// works here, but it is the wrong tool List<String> shortNames = new ArrayList<>(); names.stream() .filter(n -> n.length() <= 5) .forEach(n -> shortNames.add(n)); System.out.println("forEach + add: " + shortNames);
// the stream builds the list itself List<String> better = names.stream() .filter(n -> n.length() <= 5) .toList(); System.out.println("toList(): " + better); System.out.println("How many: " + names.stream().filter(n -> n.length() <= 5).count()); }}forEach + add: [Aarav, Priya, Kavya] toList(): [Aarav, Priya, Kavya] How many: 3
What this code does
- Both lists look the same here, so the bug is hidden. The first version depends on a side effect: the lambda changes
shortNames, which lives outside the stream. Switch toparallelStream()and threads add at the same time, losing names or throwing an exception. toList()lets the stream build the list safely, sequential or parallel, and the code says what it means: "give me the short names".
A counter like passed++ inside the lambda does not even compile: a lambda can only read local variables that are effectively final. Adding to an outside ArrayList compiles and works on a normal stream, but it hides the intent. On a parallel stream, several threads call add on the same ArrayList at once, so elements get lost or the program throws an exception. The fix is to let the stream produce the answer: count() for a number and toList() for a list. A later lesson in this module covers toList() in detail.
- Printing, logging, sending an SMS:
forEachis right. - How many:
filter(...).count(). - A new list:
filter(...).map(...).toList(), neverforEach(list::add). - Order matters on a parallel stream:
forEachOrdered.
Next step
Check your understanding
10 quick questions