Exploring the forEach Method in Java 8 Stream API

--

Java 8 introduced the Stream API, a powerful and expressive way to work with collections. Among its many methods, the forEach method stands out as a concise and versatile tool for iterating over elements in a stream. In this blog post, we'll dive into the forEach method, understand its syntax, and explore various examples showcasing its applications.

Understanding forEach

The forEach method is a terminal operation in the Stream API, meaning it triggers the processing of elements in the stream. It takes a single argument—a lambda expression or a method reference—representing the action to be performed on each element.

The syntax for forEach is as follows:

stream.forEach(element -> action);

Here, stream is the source stream, element represents each element in the stream, and action is the operation applied to each element.

Basic Usage

Let’s start with a simple example to illustrate the basic usage of forEach. Consider a list of strings:

List<String> fruits = Arrays.asList("Apple", "Banana", "Orange");

fruits.stream().forEach(fruit -> System.out.println(fruit));

This code prints each fruit in the list to the console. The lambda expression (fruit -> System.out.println(fruit)) is the action applied to each element.

Modifying Elements

forEach is not limited to printing elements; it can also be used to modify elements within the stream. For example, let's square each number in a list:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

numbers.stream().forEach(num -> {
int squared = num * num;
System.out.println(squared);
});

In this case, the lambda expression squares each number and prints the result. This demonstrates how forEach facilitates both iteration and modification.

Updating External Variables

The lambda expression used in forEach can access and update external variables. Let's calculate the sum of a list of numbers:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = 0;

numbers.stream().forEach(num -> {
sum += num; // Updating external variable
});

System.out.println("Sum of numbers: " + sum);

Here, the lambda expression updates the external variable sum, accumulating the sum of all numbers in the list.

Method References

In addition to lambda expressions, forEach supports method references. Using method references can make the code more concise. For instance:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

names.stream().forEach(System.out::println);

This example prints each name in the list using a method reference to System.out.println.

Conclusion

The forEach method in the Java 8 Stream API provides a convenient way to iterate over elements and perform actions on each element in a concise manner. Whether you're printing elements, modifying them, or updating external variables, forEach proves to be a versatile tool in stream processing. Its integration with lambda expressions and method references adds to the expressive power of Java 8 and beyond. As you explore the Stream API, mastering forEach will undoubtedly enhance your ability to work with collections in a more functional and expressive style.

Thanks & Happy Learning :)

--

--

No responses yet