Wednesday, January 28, 2009

Iterating through a Collection in Java

There are three common ways to iterate through a Collection in Java using either while(), for() or for-each(). While each technique will produce more or less the same results, the for-each construct is the most elegant and easy to read and write. It doesn't require an Iterator and is thus more compact and probably more efficient. It is only available since Java 5 so you can't use it if you are restrained to Java 1.4 or earlier. Following, the three common methods for iterating through a Collection are presented, first using a while loop, then a for loop, and finally a for-each loop. The Collection in this example is a simple ArrayList of Strings.



While
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class WhileIteration {

public static void main(String[] args) {

Collection<String> collection = new ArrayList<String>();

collection.add("zero");
collection.add("one");
collection.add("two");

Iterator iterator = collection.iterator();

// while loop
while (iterator.hasNext()) {
System.out.println("value= " + iterator.next());
}
}
}




For
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ForIteration {

public static void main(String[] args) {

Collection<String> collection = new ArrayList<String>();

collection.add("zero");
collection.add("one");
collection.add("two");

// for loop
for (Iterator<String> iterator = collection.iterator(); iterator.hasNext();) {
System.out.println("value= " + iterator.next());
}
}
}



For-Each
import java.util.ArrayList;
import java.util.Collection;

public class ForEachInteration {

public static void main(String[] args) {

Collection<String> collection = new ArrayList<String>();

collection.add("zero");
collection.add("one");
collection.add("two");

// for-each loop
for (String s : collection) {
System.out.println("value= " + s);
}
}
}


The result for each method should look like this:
value= zero
value= one
value= two


2 comments:

dimitar said...

Hmm... I have not actively used Java for some time now, even though I am a certified Java programmer. But I guess you learn something every day.
The for-each loop looks cool, but I wonder who had the need to make that a part of the language.

The for, while and do-while loops were completely sufficient to do anything you needed to.

The for-each loop looks like a plain old VB structure.

I hope they do not pull towards the crappy VB syntax and continue the C/C++ syntax.

JE @ dojo ajax request said...
This comment has been removed by a blog administrator.