Java forEach() executes an action for every element in an Iterable, collection, map, or stream. This tutorial explains the forEach() syntax and demonstrates its use with a List, Set, Map, array, method reference, and stream.
Java forEach() Method
Java forEach() is used to execute a set of statements for each element in a data source. It is commonly used with collections such as List and Set, with Map entries, and with Java streams.
The Iterable.forEach() method accepts a Consumer. A consumer receives one element and performs an action without returning a result. The Map.forEach() method accepts a BiConsumer, which receives a key and its corresponding value.
In this Java Tutorial, we shall look into examples that demonstrate the usage of forEach(); function for some of the collections like List, Map and Set.
Java forEach() Syntax for Iterable Collections
The syntax of foreach() function is:
elements.foreach(element -> {
//set of statements
});
where elements is the collection and set of statements are executed for each element. element could be accessed in the set of statements.
In Java source code, the method name is case-sensitive and is written as forEach(). The general form is shown below.
elements.forEach(element -> {
// statements executed for each element
});
If there is only one statement you would like to execute for each element, you can write the code as shown below.
elements.foreach(element -> statement);
The corresponding Java syntax with the correct method name is:
elements.forEach(element -> statement);
Braces are optional when the lambda body contains only one statement. Use braces when the action contains multiple statements, conditions, or local variables.
Java forEach() with a List
Example 1 – Java forEach – List
In this example, we shall take Java List and write two forEach statements for the list. In the first forEach, we shall execute a single statement, like printing the value. In the second forEach statement, we shall execute an if-else loop for each of the element in the list.
Example.java
import java.util.List;
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
List<String> nameList = new ArrayList<String>();
nameList.add("Java");
nameList.add("Kotlin");
nameList.add("Android");
// only single statement to be executed for each item in the ArrayList
nameList.forEach(name -> System.out.println(name) );
// multiple statements to be executed for each item in the ArrayList
nameList.forEach(name -> {
if(name.equals("Android")) {
System.out.println(name + " is a framework.");
} else {
System.out.println(name + " is a programming language.");
}
});
}
}
Output
Java
Kotlin
Android
Java is a programming language.
Kotlin is a programming language.
Android is a framework.
An ArrayList normally processes elements in their list order. The lambda parameter name represents the current list element during each invocation.
Java forEach() with a Set
Example 2 – Java forEach – Set
In this example, we have taken a Java Set, and executed a single statement for each of the element in the list using first forEach. And in the second forEach, we have executed an if-else statement for each of the element in the set.
Example.java
import java.util.HashSet;
import java.util.Set;
public class Example {
public static void main(String[] args) {
Set<String> nameList = new HashSet<String>();
nameList.add("Java");
nameList.add("Kotlin");
nameList.add("Android");
// only single statement to be executed for each item in the HashSet
nameList.forEach(name -> System.out.println(name) );
// multiple statements to be executed for each item in the HashSet
nameList.forEach(name -> {
if(name.equals("Android")) {
System.out.println(name + " is a framework.");
} else {
System.out.println(name + " is a programming language.");
}
});
}
}
Output
Java
Kotlin
Android
Java is a programming language.
Kotlin is a programming language.
Android is a framework.
A HashSet does not guarantee iteration order. The same elements may therefore appear in a different order on another run or Java implementation. Use an ordered set implementation when predictable traversal order is required.
Java Map forEach() with Keys and Values
Example 3 – Java forEach – Map
In this example, we used Java forEach function on the elements of Map.
Map.forEach() supplies two lambda parameters: the current key and the value associated with that key.
Example.java
import java.util.*;
public class Example {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(10, "Java");
map.put(20, "Kotlin");
map.put(30, "Android");
// only single statement to be executed for each item in the Map
map.forEach( (key,value) -> System.out.println(key+":"+value) );
// multiple statements to be executed for each item in the Map
map.forEach((key,value) -> {
if(value.equals("Android")) {
System.out.println(value + " is a framework.");
} else {
System.out.println(value + " is a programming language.");
}
});
}
}
Output
20:Kotlin
10:Java
30:Android
Kotlin is a programming language.
Java is a programming language.
Android is a framework.
A HashMap does not promise a specific traversal order. Do not write program logic that depends on the order shown in this output.
Java forEach() with a Method Reference
When the lambda only passes its argument to an existing compatible method, a method reference can make the statement shorter. The following example prints every list element with System.out::println.
Example.java
import java.util.Arrays;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> names = Arrays.asList("Java", "Kotlin", "Android");
names.forEach(System.out::println);
}
}
Output
Java
Kotlin
Android
The method reference above is equivalent to names.forEach(name -> System.out.println(name)).
Java forEach() for an Array
Java arrays do not define a forEach() method. To process an array with forEach(), convert it to a stream with Arrays.stream(). For simple array traversal, the enhanced for loop is also a direct option.
Example.java
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
String[] names = {"Java", "Kotlin", "Android"};
Arrays.stream(names)
.forEach(System.out::println);
}
}
Output
Java
Kotlin
Android
Java Stream forEach() with Filtering
Stream.forEach() is usually placed at the end of a stream pipeline. Intermediate operations such as filter() and map() prepare the elements before the terminal forEach() action runs.
Example.java
import java.util.Arrays;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> names = Arrays.asList(
"Java", "Kotlin", "Android", "JavaScript");
names.stream()
.filter(name -> name.startsWith("Java"))
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Output
JAVA
JAVASCRIPT
Java forEach() versus Enhanced for Loop
Both forms can process each element in a collection, but they suit different kinds of logic.
| Requirement | Prefer |
|---|---|
| Apply a short action to every element | forEach() |
| Use a method reference | forEach() |
| Work at the end of a stream pipeline | Stream.forEach() |
Use break or continue | Enhanced for loop |
| Return immediately from the surrounding method during traversal | Enhanced for loop |
| Need the element index | Traditional indexed for loop |
| Handle checked exceptions directly | Loop, or a helper method that handles the exception |
Neither form is universally better. Choose the form that expresses the required control flow clearly. A conventional loop is generally clearer when traversal requires early termination, index access, or complex branching.
Java forEach() Limitations and Common Errors
forEach() cannot use break or continue
A lambda passed to forEach() is not a loop body in which Java permits break or continue. Use an enhanced or traditional for loop when iteration must stop early or skip directly to the next loop iteration.
A return statement returns from the lambda
A plain return; inside a forEach() lambda returns from that lambda invocation. It does not terminate the enclosing method or stop the remaining elements from being processed.
Do not structurally modify a collection during forEach()
Adding or removing elements from the same collection while it is being traversed can cause a ConcurrentModificationException or other unsupported behavior. Use an iterator where appropriate, collect the required changes separately, or use methods such as removeIf() for matching removal operations.
Parallel stream forEach() may not preserve encounter order
With a parallel stream, forEach() may process elements in a different order. Use forEachOrdered() when the stream has an encounter order and that order must be respected.
names.parallelStream().forEachOrdered(System.out::println);
Java forEach() FAQs
What is forEach() in Java?
forEach() is a method that accepts an action and invokes that action for every element. For an Iterable, the action is represented by a Consumer. For a Map, it is represented by a BiConsumer that receives a key and value.
Which is better in Java: a for loop or forEach()?
Use forEach() for a concise action applied to every element. Use a for loop when you need an index, break, continue, early return from the enclosing method, or detailed control over traversal.
Can Java forEach() be used with an array?
An array does not have its own forEach() method. Use Arrays.stream(array).forEach(...), or use an enhanced for loop directly on the array.
How do I access both the key and value in Map.forEach()?
Declare two lambda parameters: map.forEach((key, value) -> action). The first parameter receives the current key and the second receives its mapped value.
Does Java forEach() preserve element order?
It follows the traversal characteristics of the source. A List normally has a defined order, while HashSet and HashMap do not guarantee iteration order. Parallel-stream forEach() also does not guarantee encounter order.
Java forEach() Editorial QA Checklist
- Verify that the Java method name is written as the case-sensitive
forEach(), notforeach(). - Confirm that List and Set examples use one lambda parameter, while Map examples use key and value parameters.
- Do not promise a fixed output order for
HashSet,HashMap, or parallel-streamforEach(). - Use a conventional loop when an example requires
break,continue, an index, or early method return. - Check that examples do not add or remove elements from the same collection during
forEach()traversal.
Summary of Java forEach()
In this Java Tutorial, we learned how to use Java forEach() with a List, Set, Map, array stream, method reference, and stream pipeline. forEach() is suitable when an action must run for every element. A regular for loop remains the clearer choice when traversal requires an index, early termination, or explicit loop control.
TutorialKart.com