Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) {  } 
like image 219
Jason Rogers Avatar asked Mar 08 '11 05:03

Jason Rogers


People also ask

Can you iterate through an ArrayList Java?

The iterator can be used to iterate through the ArrayList wherein the iterator is the implementation of the Iterator interface. Some of the important methods declared by the Iterator interface are hasNext() and next().

Which collection is better to use for iterating over?

HashMap ( HashSet uses HashMap<E,Object> ) isn't designed for iterating all items. The fastest way to iterate over HashMap is a combination of Iterator and the C style for loop, because JVM doesn't have to call hasNext() .

Which ArrayList method should you use to control the for loop iterations?

We can iterate on Java ArrayList using foreach loop introduced in Java 5, by far most clean method until you don't need to remove elements from ArrayList in that case you must use Java Iterator for looping or iterating over ArrayList.


2 Answers

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).

like image 185
MAK Avatar answered Sep 20 '22 19:09

MAK


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++)

like image 32
Suraj Chandran Avatar answered Sep 20 '22 19:09

Suraj Chandran