ZetCode

Java forEach

last modified July 3, 2024

In this article we shows how to use Java forEach method. We work with consumers and demonstrate forEach on lists, map, and set collections.

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. It provides programmers a new, concise way of iterating over a collection.

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.

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

void main() {

    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.

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

void main() {

    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.

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

void main() {

    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.

In the next example, we explicitly show the Consumer and the Map.Entry in code.

Main.java
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

void main() {

    HashMap<String, Integer> map = new HashMap<>();

    map.put("cups", 6);
    map.put("clocks", 2);
    map.put("pens", 12);

    Consumer<Map.Entry<String, Integer>> action = entry ->
    {
        System.out.printf("key: %s", entry.getKey());
        System.out.printf(" value: %s%n", entry.getValue());
    };

    map.entrySet().forEach(action);
}

The example loops on a entry set, which is retrieved via entrySet.

Java forEach on Set

The following example uses forEach on a set.

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

void main() {

    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.

Main.java
import java.util.Arrays;

void main() {

    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.

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

void main() {

    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

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

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

void main() {

    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.

Source

Java language basics - tutorial

In this article we have presented the Java forEach method. We have introduced consumers and used forEach on lists, maps, and set.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials.