Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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:

  1. Use forEach() at the end of a stream pipeline.
  2. Pass a Consumer lambda to define the action for each element.
  3. 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.