Java 8 forEach with List, Set and Map Examples

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

  1. Java 8 Lambda Expressions
  2. Java 8 Functional Interfaces
  3. Java 8 Method References
  4. Java 8 Stream API
  5. Java 8 Optional Class
  6. Java 8 Collectors Class
  7. Java 8 StringJoiner Class
  8. Java 8 Static and Default Methods in Interface
  9. Guide to Java 8 forEach Method
  10. Handle NullPointerException using Java 8 Optional Class
  11. How to Use Java 8 Stream API in Java Projects
  12. Migrating Source Code to Java 8

Comments