Site Search:

Iterate using forEach methods of Streams and List

Back>

stream.forEach()
stream.forEach()


Let's study Stream.forEach and Iterable.forEach.

OCPJP>cat ForEachDemo.java 
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Stream;

public class ForEachDemo{
    public static void main(String...args) {
        
        List<Integer> list = new ArrayList<>();
        
        Consumer<Integer> printIt = System.out::print;
        Consumer<Integer> storeIt = list::add;
        
        System.out.println("\nprint a stream data with forEach");
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
        stream.forEach(printIt);
        
        System.out.println("\nstore a stream data to a particular list with forEach");
        stream = Stream.of(1, 2, 3, 4, 5);
        stream.forEach(storeIt);
        
        System.out.println("\nthere are many ways to loop a list");
        
        System.out.println("Using list.iterator");
        Iterator<Integer> iter = list.iterator();
        while(iter.hasNext()) {
            System.out.print(iter.next());
        }
        
        System.out.println("\nUsing implicit for loop");
        for (Integer i : list) {
            System.out.print(i);
        }
        
        System.out.println("\nUsing explicit for loop");
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i));
        }
        
        System.out.println("\nUsing Iterable.forEach");
        list.forEach(printIt);
        
        System.out.println("\nUsing Stream.forEach");
        list.stream().forEach(printIt);
    }
}
OCPJP>javac ForEachDemo.java 
OCPJP>java ForEachDemo

print a stream data with forEach
12345
store a stream data to a particular list with forEach

there are many ways to loop a list
Using list.iterator
12345
Using implicit for loop
12345
Using explicit for loop
12345
Using Iterable.forEach
12345
Using Stream.forEach
12345OCPJP>


Several things to pay attention to:

forEach as the name suggests: Performs an action for each element (of Stream or Collection).
void forEach(Consumer<? super T> action)

The forEach method parameter is a lamda expression (Consumer), it's return type is void. So we use forEach merely for its side effect instead of returned value.
Consumer is a lamda function that takes a parameter, returns nothing. In another word, by calling forEach, we are consuming the stream elements.

Working on infinite stream with forEach will take forever and hang your program.