![]() |
VOOZH | about |
The IntStream forEach() method in Java is a terminal operation that performs a given action on each element of the stream. It is commonly used to iterate through primitive int values in a functional style introduced in Java 8.
void forEach(IntConsumer action)
Parameter: IntConsumer action: This is a functional interface that accepts a single int-valued argument and performs an operation without returning any result.
Important Points:
Example 1: Using IntStream.of()
7 8 9 10
Explanation: This example creates an IntStream with fixed values 7, 8, 9, 10. The forEach method prints each number in the same order.
Example 2: Using IntStream.range() on a Sequential Stream
4 5 6 7 8
Explanation: This example uses IntStream.range(4, 9) to create numbers from 4 to 8. The forEach prints them in order because it is a sequential stream.
Example 3: Using IntStream.range() with Parallel Stream
6 8 7 5 4
Example: This example uses parallel() on the stream, so the numbers may print out of order.
Note: In parallel streams, the output order is not fixed due to concurrent execution.
To know quickly about this method and why we use this method, then refer the below table:
Feature | Description |
|---|---|
Method | forEach(IntConsumer action) |
Type | Terminal Operation |
Stream Type | Sequential and Parallel |
Order | Only in Sequential Streams |
Use Case | Perform side-effects like printing or logging |