Open In App

Iterable forEach() method in Java with Examples

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

It has been Quite a while since Java 8 released. With the release, they have improved some of the existing APIs and added few new features. One of them is forEach Method in java.lang.Iterable Interface.

Whenever we need to traverse over a collection we have to create an Iterator to iterate over the collection and then we can have our business logic inside a loop for each of the elements inside the collection. We may greeted with ConcurrentModificationException if it is not implemented properly.

The implementation of forEach method in Iterable interface is:

default void forEach(Consumer action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

Parameter: This method takes a parameter action of type java.util.function.Consumer which represents the action to be performed for each element.

Returns: The return type of forEach is void. Hence it do not returns anything.

Exception: Throws NullPointerException if the input action is null.

Program 1: Program to iterate a list of String using the Iterator.




// Java program to demonstrate
// forEach() method of Iterable interface
  
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
  
public class ForEachExample {
  
    public static void main(String[] args)
    {
        List<String> data = new ArrayList<>();
        data.add("New Delhi");
        data.add("New York");
        data.add("Mumbai");
        data.add("London");
  
        Iterator<String> itr = data.iterator();
        while (itr.hasNext()) {
  
            System.out.println(itr.next());
            // data.remove(itr.next());
            // this line can introduce you to
            // java.util.ConcurrentModificationException.
        }
    }
}


Output:

New Delhi
New York
Mumbai
London

Program 2: Program to demonstrate forEach() method on a List which contains list of cities.




// Java program to demonstrate
// forEach() method of Iterable interface
  
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
  
public class ForEachExample {
  
    public static void main(String[] args)
    {
        List<String> data = new ArrayList<>();
        data.add("New Delhi");
        data.add("New York");
        data.add("Mumbai");
        data.add("London");
  
        data.forEach(new Consumer<String>() {
  
            @Override
            public void accept(String t)
            {
  
                System.out.println(t);
            }
  
        });
    }
}


Output:

New Delhi
New York
Mumbai
London

In the above program, we have created a List of String with 4 elements and then we have iterated over the list using the forEach method. As described earlier forEach method take Consumer object as input, we have created an anonymous inner class implementation of Consumer interface and overrides the accept method. In this example, we have kept the business logic inside the anonymous inner class and we can not reuse it.

Program 3: In this program we will demonstrate the implementation of Consumer interface separately so that we can reuse it. Let’s create a class CityConsumer which implements Consumer interface and overrides its accept method.




// Java program to demonstrate
// forEach() method of Iterable interface
  
import java.util.*;
import java.util.function.Consumer;
  
class CityConsumer implements Consumer<String> {
  
    @Override
    public void accept(String t)
    {
        System.out.println(t);
    }
}
  
// Now we can use the CityConsumer
// with forEach method by just creating
// an object of CityConsumer class as below.
  
public class ForEachExample {
  
    public static void main(String[] args)
    {
        List<String> data = new ArrayList<>();
        data.add("New Delhi");
        data.add("New York");
        data.add("Mumbai");
        data.add("London");
  
        // create an object of CityConsumer
        // and pass it to forEach method
        CityConsumer cityConsumer = new CityConsumer();
        data.forEach(cityConsumer);
    }
}


Output:

New Delhi
New York
Mumbai
London

Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html



Last Updated : 22 May, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads