Java 8 forEach tutorial

Java 8 forEach tutorial shows how to use Java 8 forEach() method. We work with consumers and demonstrate forEach() on lists, map, and set collections.

The forEach() method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection.

The forEach() method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

void forEach(Consumer<? super T> action);

This is the syntax of the forEach() method.

Consumer interface

The Consumer interface is a functional interface (an interface with a single abstract method), which accepts a single input and returns no result.

@FunctionalInterface
public interface Consumer {
    void accept(T t);
}

This is the definition of the Consumer interface.

JavaForEachListConsumer.java
package com.zetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class JavaForEachListConsumer {

    public static void main(String[] args) {

        List<String> items = new ArrayList<>();

        items.add("coins");
        items.add("pens");
        items.add("keys");
        items.add("sheets");

        items.forEach(new Consumer<String>() {
            @Override
            public void accept(String name) {
                System.out.println(name);
            }
        });
    }
}

In this example, we iterate over a list of strings with forEach(). This syntax can be shortened with Java lambda expression.

Lambda expression

Lambda expressions are used primarily to define an inline implementation of a functional interface, i.e., an interface with a single method only. Lambda expression are created with the -> lambda operator.

JavaForEachListLambda.java
package com.zetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class JavaForEachListLambda {

    public static void main(String[] args) {

        List<String> items = new ArrayList<>();

        items.add("coins");
        items.add("pens");
        items.add("keys");
        items.add("sheets");

        items.forEach((String name) -> {
            System.out.println(name);
        });
    }
}

Here we have the same example. The lambda expression makes the example more concise.

Using forEach on Map

The following example uses forEach() on a map.

JavaForEachMap.java
package com.zetcode;

import java.util.HashMap;
import java.util.Map;

public class JavaForEachMap {

    public static void main(String[] args) {

        Map<String, Integer> items = new HashMap<>();

        items.put("coins", 3);
        items.put("pens", 2);
        items.put("keys", 1);
        items.put("sheets", 12);

        items.forEach((k, v) -> {
            System.out.printf("%s : %d%n", k, v);
        });
    }
}

We have a map of string/integer pairs. With the forEach() method, we iterate over the map and print its key/value pairs.

Using forEach on Set

The following example uses forEach() on a set.

JavaForEachSet.java
package com.zetcode;

import java.util.HashSet;
import java.util.Set;

public class JavaForEachSet {

    public static void main(String[] args) {
        
        Set<String> brands = new HashSet<>();
        
        brands.add("Nike");
        brands.add("IBM");
        brands.add("Google");
        brands.add("Apple");
        
        brands.forEach((e) -> { System.out.println(e); });
    }
}

We have a set of strings. With the forEach() method, we iterate over the set and print its values.

Using forEach on Array

The following example uses forEach() on an array.

JavaForEachArray.java
package com.zetcode;

import java.util.Arrays;

public class JavaForEachArray {

    public static void main(String[] args) {
        
        int[] nums = { 3, 4, 2, 1, 6, 7 };
        
        Arrays.stream(nums).forEach((e) -> { System.out.println(e); });
    }
}

In the example, we have an array of integers. We use Arrays.stream() method to transform the array into a stream. The forEach() method then iterates over the elements and prints them to the console.

Filtering a list

We can easily filter our data before traversing them with forEach().

JavaForEachListFilter.java
package com.zetcode;

import java.util.ArrayList;
import java.util.List;

public class JavaForEachListFilter {

    public static void main(String[] args) {

        List<String> items = new ArrayList<>();

        items.add("coins");
        items.add("pens");
        items.add("keys");
        items.add("sheets");

        items.stream().filter(item -> (item.length() == 4)).forEach(System.out::println);
    }
}

In this example, we filter a list of strings and print the filtered list to the console. Only strings having four characters are shown.

IntConsumer, LongConsumer, DoubleConsumer

Java 8 provides built-in consumer interfaces for primitive data types: IntConsumer, LongConsumer and DoubleConsumer.

JavaForEachConsSpec.java
package com.zetcode;

import java.util.Arrays;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;

public class JavaForEachConsSpec {

    public static void main(String[] args) {

        int[] inums = { 3, 5, 6, 7, 5 };
        IntConsumer icons = i -> System.out.print(i + " ");
        Arrays.stream(inums).forEach(icons);
        
        System.out.println();

        long[] lnums = { 13l, 3l, 6l, 1l, 8l };
        LongConsumer lcons = l -> System.out.print(l + " ");
        Arrays.stream(lnums).forEach(lcons);
        
        System.out.println();

        double[] dnums = { 3.4d, 9d, 6.8d, 10.3d, 2.3d };
        DoubleConsumer dcons = d -> System.out.print(d + " ");
        Arrays.stream(dnums).forEach(dcons);
        
        System.out.println();
    }
}

In the example, we create the three types of consumers and iterate over them with forEach().

In this tutorial, we have presented the Java 8 forEach() method. We have introduced consumers and used forEach() on lists, map, and set.

You might also be interested in the following related tutorials: Java tutorial, Joining strings with Java 8's StringJoiner, Introduction to Google Guava, Filtering a list in Java, or Android tutorial.