IntStream forEach() Method in Java
Last Updated :
06 May, 2025
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.
Syntax of IntStream forEach() Method
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:
- The forEach() is a terminal operation means the stream gets consumed and cannot be reused.
- It can be used on both sequential and parallel streams.
- In parallel streams, the behavior of this operation is explicitly nondeterministic. Also, for any given element, the action may be performed at any time and in any thread the library chooses.
Example 1: Using IntStream.of()
Java
// Java program to demonstrate
// IntStream.forEach(IntConsumer action)
import java.util.stream.IntStream;
public class Geeks {
public static void main(String[] args) {
// Creating an IntStream with specific values
IntStream stream = IntStream.of(7, 8, 9, 10);
// Using forEach to print each element
stream.forEach(System.out::println);
}
}
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
Java
// Java program to demonstrate
// IntStream.forEach on a range
import java.util.stream.IntStream;
public class Geeks {
public static void main(String[] args) {
// Creating an IntStream from 4 to 8 (9 is exclusive)
IntStream stream = IntStream.range(4, 9);
// Using forEach to print each element in order
stream.forEach(System.out::println);
}
}
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
Java
// Java program to demonstrate non-deterministic
// behavior using parallel stream
import java.util.stream.IntStream;
public class Geeks {
public static void main(String[] args) {
// Creating an IntStream from 4 to 8
IntStream stream = IntStream.range(4, 9);
// Using parallel stream — order of output is not guaranteed
stream.parallel().forEach(System.out::println);
}
}
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 |
---|