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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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<string> iterator = collection.iterator(); // while loop while (iterator.hasNext()) { System.out.println("value= " + iterator.next()); } } } |
For
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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); } } } |
Result
The result for each method should look like this:
1 2 3 |
value= zero value= one value= two |
Are you interested in the cutting edge of AI processors? Read how to build the Ex-Machina Wetware Brain and learn about the Knowm Technology Stack.
Subscribe To Our Newsletter
Join our low volume mailing list to receive the latest news and updates from our team.