Java 8 FAQ: Top Questions
16. How does the forEach() method work in Java 8 Streams?
The forEach()
method is a terminal operation in Java 8 Streams that performs an action on each element of the stream. It is commonly used to print or apply a side-effect on elements of a stream.
πΊοΈ Step-by-Step Instructions:
- Use
forEach()
at the end of a stream pipeline. - Pass a
Consumer
lambda to define the action for each element. - This method does not return a result and is considered side-effecting.
π₯ Example Input:
List names = Arrays.asList("Java", "Python", "C++");
names.stream()
.forEach(name -> System.out.println("Language: " + name));
π Expected Output:
Language: Java
Language: Python
Language: C++
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class StreamForEachExample {
public static void main(String[] args) {
List names = Arrays.asList("Java", "Python", "C++");
names.stream()
.forEach(name -> System.out.println("Language: " + name));
}
}
π Detailed Explanation:
- forEach(): Applies a
Consumer
to each stream element. - Terminal operation: Ends the stream pipeline.
- Side-effects: Used for logging, printing, or updating external state (use with care).
π οΈ Use Cases:
- Displaying or logging stream contents.
- Applying non-transforming operations like metrics or counters.
- Iterating over filtered or mapped results directly.