Java 8 forEach method in Iterable Interface

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 Java 8 forEach method in java.lang.Iterable Interface.

The implementation of the forEach method in the Iterable interface is:

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

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 be greeted with ConcurrentModificationException if it is not implemented properly.

See the below code snippet.

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.
		}
	}
}

Java 8 has introduced the forEach method in the Iterable interface which takes a java.util.function.Consumer
Object as an input. It helps us write our business logic at a separate location so that we can reuse it.

Let’s see a simple implementation of forEach:

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);
		    }
		     
		});
	}
}

The output will be:

New Delhi
New York
Mumbai
London

In the above example, 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 the Consumer object as input, we have created an anonymous inner class implementation of the 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. Now let’s make the Consumer implementation separately that can be reused.

To implement Consumer implementation separately create a class that implements the Consumer interface and overrides its accept method as shown below.

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.

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");
		
		CityConsumer cityConsumer = new CityConsumer();
		data.forEach(cityConsumer);

	}
}

The output will be:

New Delhi
New York
Mumbai
London

Happy Learning !!!

Leave a Comment