Java Program to Iterate over a List

In this post, we will discuss various methods to iterate over a List in Java.


 

1. Using List.toString()

If we simply want to display contents of the list, we can do that by converting list to a string using toString() function and then simply printing it as shown below:

Java

Download   Run Code

2. Using ListIterator or Iterator

The List interface provides a special iterator, called a ListIterator, that allows bidirectional access in addition to the normal operations that the Iterator interface provides. We can call List.listIterator() to get a ListIterator over the elements in a list. We can also use List.iterator() that returns an Iterator.

Java

Download   Run Code

Generic

Download   Run Code

3. Using for loop / enhanced for loop:

We know that List is an ordered collection, so we can access elements by their index in the list using a for loop.

The for loop also has another form designed for iteration through Collections and arrays called enhanced for loop. We can also use enhanced for to loop through the list.

Java

Download   Run Code

4. Java 8 – using Streams and Lambda

In Java 8, we can loop a List with the help of streams, lambdas and forEach. Below program shows 4 ways to do that –

Java

Download   Run Code

5. Converting List to Array

We can also convert the list to an array using List.toArray(T[ ]) method and then iterating over the array using a for loop or print it using Arrays.toString(). There are several other implementations of toArray() method as shown below:

Java

Download   Run Code

6. Using Enumeration Interface

Finally, we can make use of deprecated Enumeration interface to print a list. This interface provides methods to enumerate through the elements of a vector. So, we need to convert our list to Vector first and then print all elements of that Vector.

Java

Download   Run Code

 
Related Post: Iterate List in Reverse Order

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz