This post will discuss various methods to iterate over a list in Java.

1. Using forEach() method

In Java 8 and above, we can use the forEach() method of the Stream API to perform an action for each element of a list. The idea is to call the stream() method to create a stream of elements, and apply a method to each element of the list using forEach(). This is similar to the enhanced for loop, but it uses a lambda expression or a method reference as an argument. For example:

Download  Run Code

2. Using a loop

We know that list is an ordered collection, so we can access elements by their index in the list using a for-loop. This is a simple and straightforward way to iterate over a list, but it requires knowing the size of the list and using a loop variable. Alternatively, we can use an enhanced for loop or for-each loop to access each element directly. This is a more concise and readable way to iterate over a list, but it does not allow modifying the list or accessing the index of the element. For example:

Download  Run Code

3. Using a ListIterator

The List interface provides a special iterator called ListIterator to access each element in either direction. This is a special type of iterator that allows iterating over a list in both forward and backward directions. A list iterator also provides methods to get the index of the current element, set or replace the current element, and insert or remove elements. We can call the List.listIterator() method to get a list iterator over the elements in a list. We can also use List.iterator() that returns an Iterator. For example:

Download  Run Code

4. Using Enumeration Interface

Finally, we can iterate over a list in Java using the Enumeration interface. We can create an Enumeration object from the list using the enumeration() method of the java.util.Collections class. Then, we can use the hasMoreElements() and nextElement() methods of the Enumeration interface to check if there are any elements left in the list and get the next element respectively. For example:

Download  Run Code

5. Using List.toString() method

To display the list’s contents to console or logs, we can use the toString() method of the List interface. This method returns the string representation of a list which consists of the list’s elements in the order they are stored in the list, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space) and each element is converted to a string using the String.valueOf() method. For example, the following code prints the string representation of the list using the toString() method.

Download  Run Code

That’s all about iterating over a List in Java.

 
Related Post:

Iterate List in reverse order in Java