In Java 8, forEach is introduced that provides an efficient way to iterate through collections ( List, Sets, and more) and Streams.
In Collection hierarchy, the iterable interface is the root interface in which a new feature has added namely forEach(). It allows iterating a collection of elements until the last element is processed.
It accepts consumer (functional interface) as an argument, meaning one needs to define a lambda expression that would take a single input and return nothing.
default void forEach(Consumer<? super T> action)
Functionality wise, forEach and enhanced for-loop are similar, but the new forEach is a type of internal loop. Meaning, the iterator handles iteration behind the scene, as a result, programmers don’t have to worry about the iteration behaviour.
Code Example:
Iterating over List:
import java.util.List; public class ForEachExample { public static void main(String[] args) { List nameList = new ArrayList(); nameList.add("Programmer"); nameList.add("ProgrammerBay"); nameList.add("coders"); nameList.forEach(singleItem -> System.out.println(singleItem)); } }
Output
Programmer ProgrammerBay coders
Iterating over Map:
import java.util.*; public class ForEachExample { public static void main(String[] args) { Map nameList = new LinkedHashMap(); nameList.put(1,"Programmer"); nameList.put(2,"ProgrammerBay"); nameList.put(4,"coders"); nameList.forEach((key,value) -> System.out.println("This is my key : "+key +" and value : "+value)); } }
Output:
This is my key : 1 and value : Programmer This is my key : 2 and value : ProgrammerBay This is my key : 4 and value : coders
Iterating over Stream of elements :
public class CreateStreams { public static void main(String[] args) { String[] stringArr = new String[]{"This", "is", "Example", "of", "Stream"}; // Creating Stream of Array Stream<String> arrayStream = Stream.of(stringArr); arrayStream.forEach(singleString -> System.out.print(singleString + " ")); } }
Output:
This is Example of Stream
Point to remember about forEach:
This post was last modified on September 20, 2020