The Wayback Machine - https://web.archive.org/web/20240618020139/https://www.geeksforgeeks.org/iterable-foreach-method-in-java-with-examples/
Open In App

Iterable forEach() method in Java with Examples

Last Updated : 22 May, 2019
Improve
Improve
Like Article
Like
Save
Share
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



Similar Reads

foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Difference Between Collection.stream().forEach() and Collection.forEach() in Java
Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working. Collection.stream().forEach() is basically used for iteration in a group of objects by converting a
3 min read
Java | Implementing Iterator and Iterable Interface
Iterators are used in Collection framework in Java to retrieve elements one by one. For more details and introduction related to this, see this link. Why it is needed to implement Iterable interface? Every class that implements Iterable interface appropriately, can be used in the enhanced For loop (for-each loop). The need to implement the Iterator
4 min read
Convert an Iterable to Collection in Java
Iterable and Collection have served to be of great use in Java. Iterators are used in Collection framework in Java to retrieve elements one by one and a Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single
4 min read
Convert an Iterable to Stream in Java
Given an Iterable, the task is to convert it into Stream in Java. Examples: Input: Iterable = [1, 2, 3, 4, 5] Output: {1, 2, 3, 4, 5} Input: Iterable = ['G', 'e', 'e', 'k', 's'] Output: {'G', 'e', 'e', 'k', 's'} Approach: Get the Iterable. Convert the Iterable to Spliterator using Iterable.spliterator() method. Convert the formed Spliterator into S
1 min read
Convert Iterator to Iterable in Java
Given an Iterator, the task is to convert it into Iterables in Java. Examples: Input: Iterator = {1, 2, 3, 4, 5} Output: {1, 2, 3, 4, 5} Input: Iterator = {'G', 'e', 'e', 'k', 's'} Output: {'G', 'e', 'e', 'k', 's'} Below are the various ways to do so: By overriding the abstract method Iterable.iterator(): Get the Iterator. Override the Iterable.ite
3 min read
Iterable Interface in Java
The Iterable interface was introduced in JDK 1.5. It belongs to java.lang package. In general, an object Implementing Iterable allows it to be iterated. An iterable interface allows an object to be the target of enhanced for loop(for-each loop). Definition of Iterable public interface Iterable&lt;T&gt; { Iterator&lt;T&gt; iterator(); Spliterator
3 min read
Stream forEach() method in Java with examples
Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer&lt;? super T&gt; action) Where, Consumer is a functional interface and T is the type of stream elements. Note
2 min read
HashTable forEach() method in Java with Examples
The forEach(BiConsumer) method of Hashtable class perform the BiConsumer operation on each entry of hashtable until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until a
2 min read
LinkedTransferQueue forEach() method in Java with Examples
The forEach() method of Java.util.concurrent.LinkedTransferQueue is an in-built function in Java which is used to traverse each element in this queue. Syntax: public void forEach(Consumer&lt;E&gt; action) Parameters: This method takes a parameter action which represents the action to be performed for each element. Return Value: This method does not
2 min read
Article Tags :
Practice Tags :