The basic “for” loop was enhanced in Java 5 and got a name “for each loop”.
It also called: Java for each loop, for in loop, advanced loop, enhanced loop.
It’s more readable and reduces a chance to get a bug in your loop.
You can use for each loop in Java to iterate through array, Collections(Set, List) or Map.
The enhanced loop works for each class that implements Iterable
interface as well.
For Each Loop Syntax in Java
The for each syntax in Java has the following form:
for (Type variable: Array) {}
Example:
int[] array = new int[]{1, 2, 3};
for (int el : array) {
System.out.println(el);
}
Since Java 8 you can use one more for each statement for Collections and Maps:
list.forEach(el -> {
System.out.println(el);
});
this can be even simplified using method reference:
list.forEach(System.out::println);
For each statement always can be represented as a basic for loop.
An array can be represented as:
int[] array = new int[]{1, 2, 3};
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
And List (or any other Iterable object) can be represented as:
List<Integer> list = Arrays.asList(1, 2, 3);
for (Iterator<Integer> i = list.iterator(); i.hasNext();) {
System.out.println(i.next());
}
Let’s take a look at code examples.
Code Examples
I prepared frequently used code examples.
For Each Loop Array
int[] array = new int[]{1, 2, 3};
for (int el : array) {
System.out.println(el);
}
Java 8 example:
int[] arr = new int[] {1, 2, 3};
Arrays.stream(arr).forEach(el -> {
System.out.println(el);
});
On my opinion, in case of an array, the 1st example is preferable.
For Each Loop ArrayList
List<String> list = new ArrayList<>();
for (String s : list) {
if (s.equals("1")) {
System.out.println(s);
}
}
On the first look Java 8 example should look like this:
list.forEach(s -> {
if (s.equals("1")) {
System.out.println(s);
}
});
But you can use the power of the Stream API and write it in one line of code:
list.stream().filter(s -> s.equals("1")).forEach(System.out::println);
For Each Loop Map
Map<String, String> map = new HashMap<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("KEY " + entry.getKey() + " AND VALUE " + entry.getValue());
}
Java 8 style:
map.forEach((key, value) -> {
System.out.println("KEY " + key + " AND VALUE " + value)
});
For Each Loop Enum
Enum.values() is array, so behavior is the same as in the 1st example.
enum Color {
RED, GREEN, BLUE
}
public static void main(String[] args) {
for (Color color : Color.values()) {
System.out.println(color);
}
}
Read about enums here.
For Each Loop Chars in String
String.toCharArray() is array, the behavior is the same as in the 1st example.
String a = "123456";
for (char c : a.toCharArray()) {
System.out.println(c);
}
For Each Loop File In Directory
File home = new File("/home");
if (home.isDirectory()) {
File[] files = home.listFiles();
if (files != null) {
for (File file : files) {
System.out.println(file.getName());
}
}
}
Java 8 style:
File home = new File("/home");
if (home.isDirectory()) {
File[] files = home.listFiles();
if (files != null) {
Arrays.stream(files).forEach(file -> {
System.out.println(file.getName());
});
}
}
or even better:
Files.list(Paths.get("/usr")).forEach(path -> {
System.out.println(path.toFile().getName());
});
For Each Loop FAQ
I collected frequently asked questions and will try to give you short answers.
Can I Remove Elements in For Each Loop
If we’re talking about not thread-safe collections like an ArrayList or HashSet than It’s not the best idea.
ConcurrentModificationException
exception will be thrown in the most cases.
You should use an iterator instead:
List<String> list = new ArrayList<>();
list.add("1");
list.add("1");
list.add("2");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if ("1".equals(next)) {
iterator.remove();
}
}
Or super simple solution since Java 8:
list.removeIf("1"::equals);
How to Get Index in For Each Loop
It’s not possible. You should use basic for loop instead.
How to Get the Last Element in For Each Loop
The same as for get index case – you should use a simple for loop instead.
How to Make Enhanced For Loop Reverse
There 2 ways:
- Use basic for loop.
- Reverse list using
Collections.reverse(listCopy)
and then apply for each loop.
References:
Do you have any questions? I hope yes ?