In java which loop is best to iterate over a collection

11,723

Solution 1

There are 3 types of loops in Java. They do different things, and with regards to Collections, have different usage.

Traditional For loop

The traditional for loop looks like:

for (int i = 0; i < list.length(); i++) {
    Object o = list.get(i);
}

It is useful when you need to use the index for something else than accessing the element, like when you have 2 loops, or when you affect the index to some value in the object.

It can be used only with lists, and even then, should never be used with LinkedLists, because get(i) is O(n) in those. It cannot be used with other Collections such as Sets.

The same syntax can also be used on arrays (use length field instead of the length() method), or on Strings (using size() and charAt)

It is usually not the best loop. It does not prevent you from messing with the i variable, or with the content of the list, which can lead to surprising results.

While loop

While loop can be used for a lot of things, but in the case of a Collection, it is used when you need to remove elements from a list. It requires an Iterator, which is a little more work:

Iterator<String> iter = coll.iterator();
while (iter.hasNext()) {
    String elem = iter.next();
    iter.remove();
}

It allows you to safely delete any element of the collection. It works on any Collection (List or Set).

It does not give you direct access to the index, but Collection and Iterable know nothing about indexed access anyway.

Fast-enum for loop

The latest addition is a short version of the above, without the possibility of removing items:

for (String elem : coll) {

}

It is the clearest. It does not involve any extra variable and works on any Iterable, as well as on arrays.

You are forbidden from modifying the collection(it will throw a ConcurrentModificationException) when looping (from inside the loop or from another thread), which guarantees the consistency of the data.

Use it whenever possible.

Solution 2

Best Way is Class Iterator use to Iterate througout the Collection but you have not mentioned Iterator

  1. I will recommend foreach loop. because in for or while or do-while there is need of defining external Counters to get end of the loop condition. but in for-each there is no need of external Variables.

  2. IndexOutOfBoundException :- It will not raise in for-each but if we type any logical mistake then other may raise this exception (in context of Array).

but if your need to play with the index then you should use for or do-while() or while().

Solution 3

First use a for-each loop when it is appropriate: iterating over the whole collection and only needing the elements (not their index).

If for-each is not appropriate then choose for-vs.-while based on whether you reasonably need the 3 parts of a for-loop, ie. use while if you would only use the condition/middle part of a for-loop.

Share:
11,723
Admin
Author by

Admin

Updated on June 20, 2022

Comments

  • Admin
    Admin almost 2 years

    What criteria should be met when deciding which of the following loops to use to iterate over elements in a collection. For example in what context will one loop be more efficient than another?

    • For Loop ??
    • While Loop ??
    • For-Each Loop ??