Introduction
Java 8 introduced the Stream API, providing a more declarative and functional approach to processing collections of data. Among the various methods available in the Stream API, forEach() is one of the most commonly used. The forEach() method allows you to iterate over each element in a stream and perform a specific action, making it used for scenarios where you need to apply a function to every element of a collection.
In this guide, we’ll explore how to use the Stream.forEach() method effectively, with examples that demonstrate its versatility in handling different types of data.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Using
forEach()with a List of Integers - Using
forEach()with a List of Strings - Using
forEach()with a Stream of Custom Objects
- Using
- Advanced Considerations
- Conclusion
Problem Statement
The task is to create a Java program that:
- Demonstrates how to use the
forEach()method to perform operations on each element in a stream. - Applies
forEach()to different types of data, including integers, strings, and custom objects. - Outputs the results of the
forEach()operations.
Example 1:
- Input: List of integers
[1, 2, 3, 4, 5] - Output: Print each integer.
Example 2:
- Input: List of strings
["apple", "banana", "cherry"] - Output: Print each string in uppercase.
Solution Steps
- Create a Stream: Start with a stream of elements (e.g., integers, strings, custom objects).
- Apply the
forEach()Method: Use theforEach()method to perform an action on each element in the stream. - Display the Result: Print or process each element as required.
Java Program
Using forEach() with a List of Integers
The forEach() method can be used to iterate over a list of integers and perform a specific action, such as printing each number.
import java.util.Arrays;
import java.util.List;
/**
* Java 8 - Using forEach() with a List of Integers
* Author: https://www.rameshfadatare.com/
*/
public class ForEachIntegerList {
public static void main(String[] args) {
// Step 1: Create a list of integers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Step 2: Use forEach() to print each number
numbers.stream()
.forEach(System.out::println);
}
}
Output
1
2
3
4
5
Explanation
- The
numbers.stream()method creates a stream from the list of integers. - The
forEach(System.out::println)method prints each number in the stream.
Using forEach() with a List of Strings
The forEach() method is also effective when working with strings. For example, you can convert each string to uppercase and then print it.
import java.util.Arrays;
import java.util.List;
/**
* Java 8 - Using forEach() with a List of Strings
* Author: https://www.rameshfadatare.com/
*/
public class ForEachStringList {
public static void main(String[] args) {
// Step 1: Create a list of strings
List<String> fruits = Arrays.asList("apple", "banana", "cherry");
// Step 2: Use forEach() to print each string in uppercase
fruits.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Output
APPLE
BANANA
CHERRY
Explanation
- The
fruits.stream()method creates a stream from the list of strings. - The
map(String::toUpperCase)method converts each string to uppercase. - The
forEach(System.out::println)method prints each uppercase string.
Using forEach() with a Stream of Custom Objects
You can use the forEach() method with custom objects, allowing you to perform actions on each object in a stream. For instance, you might want to print the name and price of each product.
import java.util.Arrays;
import java.util.List;
/**
* Java 8 - Using forEach() with a Stream of Custom Objects
* Author: https://www.rameshfadatare.com/
*/
public class ForEachCustomObjects {
public static void main(String[] args) {
// Step 1: Create a list of products
List<Product> products = Arrays.asList(
new Product("Laptop", 1500),
new Product("Phone", 800),
new Product("Tablet", 600)
);
// Step 2: Use forEach() to print each product's details
products.stream()
.forEach(product ->
System.out.println("Product: " + product.getName() + ", Price: " + product.getPrice()));
}
}
// Custom class Product
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
Output
Product: Laptop, Price: 1500.0
Product: Phone, Price: 800.0
Product: Tablet, Price: 600.0
Explanation
- The
products.stream()method creates a stream from the list ofProductobjects. - The
forEach()method is used to iterate over each product and print its name and price.
Advanced Considerations
-
Parallel Streams: The
forEach()method can be used in parallel streams. However, be cautious as the order of execution is not guaranteed in parallel streams. UseforEachOrdered()if you need to maintain the order. -
Side Effects: The
forEach()method is typically used for performing side effects, such as printing or modifying external state. Avoid usingforEach()for operations that should be purely functional (i.e., without side effects). -
Stream Finality:
forEach()is a terminal operation, meaning that after callingforEach(), the stream is considered consumed and cannot be reused.
Conclusion
This guide provides methods for using the Stream.forEach() method in Java 8, covering different types of data including integers, strings, and custom objects. The forEach() method is a powerful feature of the Stream API that allows you to apply an action to each element in a stream, making your code more concise and expressive. By understanding how to use forEach() effectively, you can simplify your data processing tasks and improve the readability of your Java applications.