开发者

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

开发者 https://www.devze.com 2023-02-15 05:46 出处:网络
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)

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开发者_如何学C 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) {

}


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


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


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


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.


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.


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

             }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号