Java 8 Stream forEach Sample

Java 8 Streams forEach operation is simplest and most widely used operation. The forEach() operation will loop over the stream elements and call the supplied function on each element.

The Stream.forEach() operation works like the standard for loop. It will iterate through each element in the stream and perform the specified operations.

Java 8 Stream forEach Sample Code

The forEach() stream operation performs an action for each element of the stream.

public class jcdStreamForEachSample {
 
    public static void main(String a[]) {
        List<String> widgets = Arrays.asList("widgetA", "widgetB", "widgetC", "widgetD", "widgetE");
        widgets.stream().forEach(System.out::println);
    }
}


Java 8 Stream forEach Output

widgetA
widgetB
widgetC
widgetD
widgetE


The Java 8 Stream forEach() operation is a terminal operation. So after the operation is completed, the stream pipeline is considered consumed, therefore can no longer be used.

Add a Comment

Your email address will not be published. Required fields are marked *