🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The forEach() method in Java, part of the java.util.stream.IntStream interface, is used to perform an action for each element of the stream. This method is useful when you need to iterate over the elements of a stream and perform a specified operation on each element.
Table of Contents
- Introduction
forEach()Method Syntax- Understanding
forEach() - Examples
- Basic Usage
- Using
forEach()with Complex Operations
- Real-World Use Case
- Conclusion
Introduction
The forEach() method is a terminal operation that applies the given action to each element of the stream. It is often used for side effects, such as printing elements, updating a data structure, or logging information.
forEach() Method Syntax
The syntax for the forEach() method is as follows:
void forEach(IntConsumer action)
Parameters:
action: AnIntConsumerthat represents the action to be performed on each element of the stream.
Returns:
- This method does not return any value.
Throws:
- This method does not throw any exceptions.
Understanding forEach()
The forEach() method processes each element of the stream and applies the specified action. This method is typically used for operations that do not produce a new stream but instead perform side effects.
Examples
Basic Usage
To demonstrate the basic usage of forEach(), we will create an IntStream and use forEach() to print each element.
Example
import java.util.stream.IntStream;
public class ForEachExample {
public static void main(String[] args) {
IntStream intStream = IntStream.of(1, 2, 3, 4, 5);
// Use forEach() to print each element
intStream.forEach(System.out::println);
}
}
Output:
1
2
3
4
5
Using forEach() with Complex Operations
This example shows how to use forEach() to perform more complex operations on each element, such as updating an external data structure.
Example
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
public class ForEachComplexExample {
public static void main(String[] args) {
IntStream intStream = IntStream.of(1, 2, 3, 4, 5);
Map<Integer, String> map = new HashMap<>();
// Use forEach() to update the map with the square of each element
intStream.forEach(n -> map.put(n, "Square: " + (n * n)));
// Print the map
map.forEach((k, v) -> System.out.println("Key: " + k + ", Value: " + v));
}
}
Output:
Key: 1, Value: Square: 1
Key: 2, Value: Square: 4
Key: 3, Value: Square: 9
Key: 4, Value: Square: 16
Key: 5, Value: Square: 25
Real-World Use Case
Logging Elements
In real-world applications, the forEach() method can be used to log each element of a stream, which is particularly useful for debugging or monitoring.
Example
import java.util.stream.IntStream;
import java.util.logging.Logger;
public class LoggingExample {
private static final Logger logger = Logger.getLogger(LoggingExample.class.getName());
public static void main(String[] args) {
IntStream intStream = IntStream.of(10, 20, 30, 40, 50);
// Use forEach() to log each element
intStream.forEach(n -> logger.info("Processing number: " + n));
}
}
Output:
Jul 03, 2024 4:17:35 AM LoggingExample lambda$main$0
INFO: Processing number: 10
Jul 03, 2024 4:17:35 AM LoggingExample lambda$main$0
INFO: Processing number: 20
Jul 03, 2024 4:17:35 AM LoggingExample lambda$main$0
INFO: Processing number: 30
Jul 03, 2024 4:17:35 AM LoggingExample lambda$main$0
INFO: Processing number: 40
Jul 03, 2024 4:17:35 AM LoggingExample lambda$main$0
INFO: Processing number: 50
Conclusion
The IntStream.forEach() method is used to perform an action for each element of the stream. This method is particularly useful for operations that involve side effects, such as printing elements, updating data structures, or logging information. By understanding and using this method, you can efficiently manage and process streams of integer values in your Java applications.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment