Java 8 provides a new method forEach in Iterable and Stream interfaces to iterate elements. forEach provides a new way of iterating elements. Classes which implement Iterable interface can use this method to iterate elements.
Syntax
1. Syntax of forEach in Iterable
default void forEach(Consumer<? super T> action)
2. Syntax of forEach in Stream
void forEach(Consumer<? super T> action)
Official documentation states the following about forEach:
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
- forEach method in Iterable interface is a
defaultmethod. - This method takes a single parameter of
Consumertype.Consumeris a functional interface.Consumerrepresents an operation that accepts a single input argument and returns no result.
@FunctionalInterface
public interface Consumer {
void accept(T t);
}
Note: Enhanced for loop is an external iterator whereas forEach is an internal iterator. In external iterator, client code controls the iteration. In internal iterator, iterator itself controls the iteration.
Let us compare the way of iterating a list of strings using enhanced for loop and forEach method.
Iteration using enhanced for loop
Before looking into forEach example to iterate, let us first see an example of for loop. We can use the enhanced for loop to iterate the list.
for (String element : listOfStrings) {
System.out.println(element);
}
Using forEach method in Java 8
Following is a simple piece of code to iterate collection of strings using forEach:
listOfStrings.forEach(element -> System.out.println(element));
forEach method takes a Consumer as a parameter. We can create a Consumer and then pass it to forEach.
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ForEachExample {
public static void main(String[] args) {
//Create a list for demo purpose
List<String> listOfStrings = Arrays.asList("one","two","three","four");
//Consumer which prints elements
Consumer<String> consumerToPrint = new Consumer<String>() {
@Override
public void accept(String t) {
System.out.println("element: " + t);
}
};
//using forEach to iterate elements
listOfStrings.forEach(consumerToPrint);
}
}
Output
element: one
element: two
element: three
element: four
Since, consumer is a functional interface, we can pass Consumer as a lambda expression.
Consumer<String> consumerToPrint = (String t) -> {
System.out.println("element: " + t);
};
We can use a method reference if a method already exists whose functionality can be used. In our example, since we are printing elements we can do the following:
listOfStrings.forEach(System.out::println);
Examples of forEach
Example 1: Iterating a list using forEach
In this example we are iterating a list in Java using forEach method.
import java.util.Arrays;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
//Create a list for demo purpose
List<String> listOfStrings = Arrays.asList("one","two","three","four");
//using forEach to iterate elements
listOfStrings.forEach(System.out::println);
}
}
Output
one
two
three
four
Example 2: Iterating a map using forEach
In this example we are iterating a map in Java using forEach method.
import java.util.HashMap;
import java.util.Map;
public class ForEachExample {
public static void main(String[] args) {
//Create a map for demo purpose
Map<Integer, String> days = new HashMap();
days.put(1, "Sunday");
days.put(2, "Monday");
days.put(3, "Tuesday");
days.put(4, "Wednesday");
//using forEach to iterate elements of map
days.forEach((key,value)-> System.out.println(key+" - "+value));
}
}
Output
1 - Sunday
2 - Monday
3 - Tuesday
4 - Wednesday
Example 3: Iterating a Stream using forEach
In this example we are iterating a Stream in Java using forEach method.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ForEachExample {
public static void main(String[] args) {
//Create a list for demo purpose
List<String> listOfStrings = Arrays.asList("one","two","three","four");
//Create a stream from list for demo
Stream<String> stream = listOfStrings.stream();
//using forEach to iterate elements
stream.forEach(System.out::println);
}
}
Output
one
two
three
four
