Java forEach
last modified January 10, 2023
Java 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.
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.
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.
Java forEach on Map
The following example uses forEach
on a map.
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.
In the next example, we explicitly show the Consumer
and the Map.Entry
in code.
package com.zetcode; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; public class ForEachMap2 { public static void main(String[] args) { 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.
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.
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
.
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
Since Java 8, we have built-in consumer interfaces for primitive data types:
IntConsumer
, LongConsumer
and DoubleConsumer
.
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 article, we have presented the Java 8 forEach
method. We have
introduced consumers and used forEach
on lists, maps, and set.
List all Java tutorials.