How do I loop through streams using forEach() method?

In Java, you can loop through a Stream by using the forEach() method provided by the Stream API.

In the following example, we created a Stream of Strings. Each String represents a different programming language. The forEach() method accepts a Consumer, which is a functional interface representing an operation that accepts a single input argument and returns no result. In this case, we passed System.out::println that acts as a Consumer to print each element in the Stream.

Here is the basic code snippet:

package org.kodejava.util;

import java.util.stream.Stream;

public class ForEachExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("Java", "Kotlin", "Scala", "Clojure");

        stream.forEach(System.out::println);
    }
}

Remember, a Stream should be operated on (invoking an action method like forEach() or collect()) only once. After that, it is consumed and cannot be used again. If you need to traverse it again, you will have to re-create.

Also, forEach() operation is a terminal operation i.e.; after applying this operation, we cannot apply any other Stream operation (neither transformation nor action) on Stream elements.

The following snippets are a few more examples using different types of data.

  • Stream of Integers
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
        stream.forEach(System.out::println);
    }
}
  • Stream from a List
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Java", "Kotlin", "Scala", "Clojure");
        Stream<String> stream = list.stream();
        stream.forEach(System.out::println);
    }
}
  • Stream from Array
import java.util.Arrays;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        String[] array = new String[] {"Java", "Kotlin", "Scala", "Clojure"};
        Stream<String> stream = Arrays.stream(array);
        stream.forEach(System.out::println);
    }
}

In these examples, I just print the elements. You can replace System.out::println with your logic. Also, you can handle exceptions inside forEach() just like a regular loop.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.