Iterating on a List in java (All possible ways)

1012


There are several ways of iterating through Lists in Java.
For a beginner this may look confusing but every way is little different from others and comes with its own advantages.

Before jumping into the solutions lets create a Java file with a list so that i can only talk about iteration code later

import java.util.ArrayList;
import java.util.List;

public class IteratingLists {
	public static void main(String[] args) {

		List<String> names = new ArrayList<>();
		names.add("name-1");
		names.add("name-2");
		names.add("name-3");
		names.add("name-4");
		names.add("name-5");

    //TODO Loop over the list here
    //TODO Fill code from one of the way described below

	}
}

1. Java 8 way (simplest way)

From Java8 onwards you can use Java's forEach to iterate on Lists and Maps.
Following is the code shows you how to iterate using forEach

names.forEach((name)->{
  System.out.println(name);
});
Limitation:

If you want to access any variables from out side of the forEach loop they should be final (effectively final) else you get compilation issues.

2. Traditional For Loop (Very Old way)

You can always use a simple for loop to loop through the elements of a List.

for (int i = 0; i < names.size(); i++) {
  System.out.println(names.get(i));
}

3. Enhanced for loop (From Java5)

From Java5 you can use the enhanced for loops. This is the most common way of iterating though lists. You can use the same way to iterate through Arrays too.

for (String name : names) {
  System.out.println(name);
}

4. Using Iterator

When your usecase is to modify the List while iterating through it. Then you have to go for Iterator else you will get ConcurrentModificationException

Iterator<String> itr = names.iterator();
while (itr.hasNext()) {
	System.out.println(itr.next());
}

5. Using while loop (Just for fun, Nobody uses it)

I am adding this just because we can. But nobody iterate through a List like this. Its better to avoid while loops as the bad code may leave you in infinite loops.

int i = 0;
while (i < names.size()) {
  System.out.println(names.get(i));
  i++;
}

Output

Following is the Output you get when you run the above program irrespective of the way you choose.

name-1
name-2
name-3
name-4
name-5