To iterate list in java is very basic operation, but over the years it’s gone through some significant changes. We will go through all these changes in given examples. For simplicity, I have created a simple list of String
as below:
List<String> list = Arrays.asList(new String[]{"One","Two","Three","Four","Five"});
Now let’s learn to iterate over it.
Iterate List with Standard for Loop
This has been in language from starting, but I am no more fan of this type of looping. It’s error prone and confusing – mostly when using greater-than
or less-than
operators.
//Using standard for loop for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
Iterate List using Iterator
Iterator is better approach than standard for loop. It uses collection framework’s own Iterator interface.
//Using Iterator Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }
Iterate List using Enhanced for Loop
This is for-loop but it hides the complexity of handling index, and so become beautiful to use.
//Using enhanced for loop for (String str : list) { System.out.println(str); }
Under the hood this form of iteration uses the Iterator
interface and calls into its hasNext
and next
methods.
Read More: Enhanced for (for-each) loop in Java
Iterate List using java 8 functional style
Tell-Don’t-Ask is a famous design principles which promotes bundling data with the functions that operate on that data (basic OOP concept). In all above example, we ask for a specific iteration to be performed instead of leaving the details of the iteration to underlying libraries and focusing on task.
Java 8 functional programming has solved this issue as well – with forEach
method which accepts a parameter of type Consumer
. As the name indicates, an instance of Consumer
will consume, through its accept
method, what’s given to it.
//Using forEach() with Consumer interface list.forEach(new Consumer<String>() { @Override public void accept(String name) { System.out.println(name); } });
Here, The forEach
method will invoke the accept
method of the given Consumer
for each element in the list
and which in turn print out the name. You can do whatever you want inside accept method.
Iterate List using java 8 lambda expression
Above forEach
method is very much effective and design-wise correct but it’s too verbose. You can use lambda expressions to trim it to more lean version of it.
//Using forEach() - lambda expression list.forEach((final String name) -> System.out.println(name));
The standard syntax for lambda expressions expects the parameters to be enclosed in parentheses, with the type information provided and comma separated. The Java compiler also offers some lenience and can infer the types. Leaving out the type is convenient, requires less effort, and is less noisy. Here type information is inferred from collection itself so you can leave that information as well.
//Using forEach() - without type information list.forEach(name -> System.out.println(name));
Now that’s great. Using this kind of iteration helps us in focusing in application logic – rather that writing unproductive code iterating over list.
Happy Learning !!