Sergio Tapia
Sergio Tapia

Reputation: 41228

Is there something better than a For loop in Java for iterating neatly through a collection?

I've been spoiled by C# with the Foreach. Is there something like this for Java?

Upvotes: 0

Views: 215

Answers (2)

Alex Zylman
Alex Zylman

Reputation: 920

Java has for...each loops also - in fact, most languages do!

You can use a for...each loop with syntax like this:

for( dataType value : collection ) { /code/ }

You can find more information, as well as code examples and demo programs, at Java's online documentation.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1504182

Yes, the enhanced for loop which was introduced in Java 1.5:

List<String> strings = getStringsFromSomewhere();
for (String x : strings)
{
    System.out.println(x);
}

It works on arrays and anything implementing Iterable<T> (or the raw Iterable type).

See section 14.14.2 of the JLS for more details.

Upvotes: 9

Related Questions