For-Each Loops in Java (Enhanced For Loop)

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:

Example:

Since Java 8 you can use one more for each statement for Collections and Maps:

this can be even simplified using method reference:

For each statement always can be represented as a basic for loop.

An array can be represented as:

And List (or any other Iterable object) can be represented as:

Let’s take a look at code examples.

Tweet For Each Loop Syntax in JavaClick To Tweet

Code Examples

I prepared frequently used code examples.

For Each Loop Array

Java 8 example:

On my opinion, in case of an array, the 1st example is preferable.

Tweet For Each Loop Array Example in JavaClick To Tweet

For Each Loop ArrayList

On the first look Java 8 example should look like this:

But you can use the power of the Stream API and write it in one line of code:

Tweet For Each Loop ArrayList Example in JavaClick To Tweet

For Each Loop Map

Java 8 style:

Tweet For Each Loop Map Example in JavaClick To Tweet

For Each Loop Enum

Enum.values() is array, so behavior is the same as in the 1st example.

Read about enums here.

Tweet For Each Loop Enum Example in JavaClick To Tweet

For Each Loop Chars in String

String.toCharArray() is array, the behavior is the same as in the 1st example.

Tweet For Each Loop Chars in String Example in JavaClick To Tweet

For Each Loop File In Directory

Java 8 style:

or even better:

Tweet For Each Loop File in Directory Example in JavaClick To Tweet

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:

Or super simple solution since Java 8:

TweetCan I Remove Elements in For Each Loop in JavaClick To Tweet

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 😉

1 Star2 Stars3 Stars4 Stars5 Stars
Loading...
Scroll Up