Java: Best way to iterate through a Collection (here ArrayList)

JavaCollectionsFor Loop

Java Problem Overview


Today I was happily coding away when I got to a piece of code I already used hundreds of times:

> Iterating through a Collection (here ArrayList)

For some reason, I actually looked at the autocompletion options of Eclipse and it got me wondering:

What cases are the following loops better to use than the others?

The classic array index loop:

for (int i = 0; i < collection.length; i++) {
  type array_element = collection.get(index);
}

The Iterator hasNext()/next():

for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
  type type = (type) iterator.next();	
}

And my favorite because its so simple to write:

for (iterable_type iterable_element : collection) {
		
}

Java Solutions


Solution 1 - Java

The first one is useful when you need the index of the element as well. This is basically equivalent to the other two variants for ArrayLists, but will be really slow if you use a LinkedList.

The second one is useful when you don't need the index of the element but might need to remove the elements as you iterate. But this has the disadvantage of being a little too verbose IMO.

The third version is my preferred choice as well. It is short and works for all cases where you do not need any indexes or the underlying iterator (i.e. you are only accessing elements, not removing them or modifying the Collection in any way - which is the most common case).

Solution 2 - Java

All of them have there own uses:

  1. If you have an iterable and need to traverse unconditionally to all of them:

    for (iterable_type iterable_element : collection)

  2. If you have an iterable but need to conditionally traverse:

    for (Iterator iterator = collection.iterator(); iterator.hasNext();)

  3. If data-structure does not implement iterable:

    for (int i = 0; i < collection.length; i++)

Solution 3 - Java

There is additionally collections’ stream() util with Java 8

collection.forEach((temp) -> {
			System.out.println(temp);
});

or

collection.forEach(System.out::println);

More information about Java 8 stream and collections for wonderers link

Solution 4 - Java

None of them are "better" than the others. The third is, to me, more readable, but to someone who doesn't use foreaches it might look odd (they might prefer the first). All 3 are pretty clear to anyone who understands Java, so pick whichever makes you feel better about the code.

The first one is the most basic, so it's the most universal pattern (works for arrays, all iterables that I can think of). That's the only difference I can think of. In more complicated cases (e.g. you need to have access to the current index, or you need to filter the list), the first and second cases might make more sense, respectively. For the simple case (iterable object, no special requirements), the third seems the cleanest.

Solution 5 - Java

The first option is better performance wise (As ArrayList implement RandomAccess interface). As per the java doc, a List implementation should implement RandomAccess interface if, for typical instances of the class, this loop:

 for (int i=0, n=list.size(); i < n; i++)
     list.get(i);

runs faster than this loop:

 for (Iterator i=list.iterator(); i.hasNext(); )
     i.next();

I hope it helps. First option would be slow for sequential access lists.

Solution 6 - Java

Here is an example

Query query = em.createQuery("from Student");
		     java.util.List list = query.getResultList();
		     for (int i = 0; i < list.size(); i++) 
		     {

			     student = (Student) list.get(i);
			     System.out.println(student.id  + "  " + student.age + " " + student.name + " " + student.prenom);
				
			 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason RogersView Question on Stackoverflow
Solution 1 - JavaMAKView Answer on Stackoverflow
Solution 2 - JavaSuraj ChandranView Answer on Stackoverflow
Solution 3 - JavasnrView Answer on Stackoverflow
Solution 4 - JavaRafe KettlerView Answer on Stackoverflow
Solution 5 - JavaAmitav PadhiView Answer on Stackoverflow
Solution 6 - JavaAbdelouhabView Answer on Stackoverflow