🎓 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
Java 8 provides a new method forEach() to iterate the elements. It is defined in the Iterable and Stream interface.
Learn and master in Java 8 features at Java 8 Tutorial with Examples.
It is a default method defined in the Iterable interface. Collection classes that extend the Iterable interface can use the forEach() loop to iterate elements.
In this post, we will learn how to forEach() method to iterate over collections, maps, and streams.
1. forEach() method with List
Let's use normal for-loop to loop a List.
public static void forEachWithList() {
final List < Person > items = new ArrayList < > ();
items.add(new Person(100, "Ramesh"));
items.add(new Person(100, "A"));
items.add(new Person(100, "B"));
items.add(new Person(100, "C"));
items.add(new Person(100, "D"));
for (final Person item: items) {
System.out.println(item.getName());
}
}
In Java 8, you can loop a List with forEach + lambda expression or method reference.
public static void forEachWithList() {
final List < Person > items = new ArrayList < > ();
items.add(new Person(100, "Ramesh"));
items.add(new Person(100, "A"));
items.add(new Person(100, "B"));
items.add(new Person(100, "C"));
items.add(new Person(100, "D"));
//lambda
items.forEach(item -> System.out.println(item.getName()));
//Output : C
items.forEach(item -> {
if ("C".equals(item)) {
System.out.println(item);
}
});
//method reference
//Output : A,B,C,D,E
items.forEach(System.out::println);
//Stream and filter
//Output : B
items.stream()
.filter(s -> s.getName().equals("Ramesh"))
.forEach(System.out::println);
}
Please refer to the comments in the above example are self-descriptive.
2. forEach() method with Map
Let's first see the normal way to loop a Map using a for-each loop.
public static void forEachWithMap() {
// Before Java 8, how to loop map
final Map < Integer, Person > map = new HashMap < > ();
map.put(1, new Person(100, "Ramesh"));
map.put(2, new Person(100, "Ram"));
map.put(3, new Person(100, "Prakash"));
map.put(4, new Person(100, "Amir"));
map.put(5, new Person(100, "Sharuk"));
for (final Entry < Integer, Person > entry: map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue().getName());
}
}
In Java 8, you can loop a Map with forEach and lambda expressions.
public static void forEachWithMap() {
// Before Java 8, how to loop map
final Map < Integer, Person > map = new HashMap < > ();
map.put(1, new Person(100, "Ramesh"));
map.put(2, new Person(100, "Ram"));
map.put(3, new Person(100, "Prakash"));
map.put(4, new Person(100, "Amir"));
map.put(5, new Person(100, "Sharuk"));
// In Java 8, you can loop a Map with forEach + lambda expression.
map.forEach((k, p) -> {
System.out.println(k);
System.out.println(p.getName());
});
}
3. forEach() method with Set
The below example shows how to use the forEach method with collections, stream, etc.
public static void forEachWithSet() {
final Set < String > items = new HashSet < > ();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
// before java 8
for (final String item: items) {
System.out.println(item);
}
// java 8 with lambda expression
//Output : A,B,C,D,E
items.forEach(item -> System.out.println(item));
//Output : C
items.forEach(item -> {
if ("C".equals(item)) {
System.out.println(item);
}
});
//method reference
items.forEach(System.out::println);
//Stream and filter
items.stream()
.filter(s -> s.contains("B"))
.forEach(System.out::println);
}
Real-World Examples
In real projects, we can use the forEach() method to loop over Java Classes to convert.
Let's create Entity class and EntityDTO class, loop over a list of entities, and convert from Entity to EntityDTO using the forEach() method.
Let's demonstrates the usage of Java 8 forEach() method real projects:
package com.ramesh.corejava.devguide.java8;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ForEachRealTimeExamples {
public static void main(String[] args) {
List < Entity > entities = getEntities();
List < EntityDTO > dtos = new ArrayList < > ();
entities.forEach(entity -> {
dtos.add(new EntityDTO(entity.getId(), entity.getEntityName()));
});
dtos.forEach(e -> {
System.out.println(e.getId());
System.out.println(e.getEntityName());
});
}
public static List < Entity > getEntities() {
List < Entity > entities = new ArrayList < > ();
entities.add(new Entity(100, "entity 1"));
entities.add(new Entity(100, "entity 2"));
entities.add(new Entity(100, "entity 3"));
return entities;
}
}
class EntityDTO {
private int id;
private String entityName;
private Date createdAt;
private String createBy;
private Date updatedAt;
private String updatedBy;
public EntityDTO(int id, String entityName) {
this.id = id;
this.entityName = entityName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
class Entity {
private int id;
private String entityName;
private Date createdAt;
private String createBy;
private Date updatedAt;
private String updatedBy;
public Entity(int id, String entityName) {
super();
this.id = id;
this.entityName = entityName;
this.createdAt = new Date();
this.createBy = "ramesh";
this.updatedAt = new Date();
this.updatedBy = "ramesh";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
The source code of this post is available on GitHub Repository.
5. Related Java 8 Top Posts
- Java 8 Lambda Expressions
- Java 8 Functional Interfaces
- Java 8 Method References
- Java 8 Stream API
- Java 8 Optional Class
- Java 8 Collectors Class
- Java 8 StringJoiner Class
- Java 8 Static and Default Methods in Interface
- Guide to Java 8 forEach Method
- Handle NullPointerException using Java 8 Optional Class
- How to Use Java 8 Stream API in Java Projects
- Migrating Source Code to Java 8
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
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment