Iterating Using forEach Methods of Streams and Lists in Java

Explore how to iterate over collections using the forEach methods of Streams and Lists in Java.

Introduction

In Java, iterating through collections is a common operation. The forEach method provides a concise and modern way to perform operations on each element of a collection. This method is available for both Stream and List, and it leverages Java's functional programming features introduced in Java 8.

forEach with List

The forEach method of the List interface accepts a lambda expression or method reference to process each element. Here's an example:


import java.util.Arrays;
import java.util.List;

public class ListForEachExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

        // Using lambda expression
        names.forEach(name -> System.out.println("Hello, " + name));

        // Using method reference
        names.forEach(System.out::println);
    }
}
            

forEach with Streams

The forEach method of the Stream interface is used to iterate over elements after applying operations like filtering or mapping. Here's an example:


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamForEachExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

        // Filter names starting with 'A' and print them
        names.stream()
             .filter(name -> name.startsWith("A"))
             .forEach(System.out::println);

        // Convert names to uppercase and print them
        names.stream()
             .map(String::toUpperCase)
             .forEach(System.out::println);
    }
}
            

Key Differences Between List and Stream forEach

  • Stateful vs Stateless: The forEach method of List directly operates on the elements of the list, while Stream's forEach processes elements of the stream pipeline.
  • Intermediate Operations: With Stream, you can apply transformations (e.g., filtering, mapping) before iteration.
  • Reusability: Streams are single-use, while Lists can be reused for multiple iterations.

When to Use Each

- Use List.forEach when you need straightforward iteration over a collection.
- Use Stream.forEach when you need to process a stream pipeline, such as applying filters, transformations, or aggregations.

Mastering the forEach methods of Streams and Lists will help you write cleaner and more expressive Java code. 

Post a Comment

0 Comments