Different Ways to Iterate an ArrayList

Learn to iterate through an ArrayList in different ways. For simplicity, we have stored five strings in the List and we will learn to iterate over it.

We can apply these iteration examples on any List, storing any type of object.

We will mainly use these five ways to loop through ArrayList.

  1. For loop
  2. Advanced for loop
  3. LisIterator
  4. While loop
  5. Java 8 Stream

1. Iterate ArrayList with ‘for loop’

Java program to iterate through an ArrayList of objects using the standard for loop.

ArrayList<String> namesList 
	= new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );

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

2. Iterate ArrayList with ‘for-each loop’

Java program to iterate through an ArrayList of objects using for-each loop.

ArrayList<String> namesList 
	= new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );

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

3. Iterate ArrayList with ListIterator

Java program to iterate through an ArrayList of objects using ListIterator interface.

ArrayList namesList
	= new ArrayList(Arrays.asList( “alex”, “brian”, “charles”) );

ListIterator listItr = namesList.listIterator();

while(listItr.hasNext())
{
	System.out.println(listItr.next());
}

4. Iterate ArrayList with ‘while loop’

Java program to iterate through an ArrayList of objects using a while loop.

ArrayList<String> namesList 
	= new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );

int index = 0;
while (namesList.size() > index)
{
   System.out.println(namesList.get(index++));
}

5. Iterate ArrayList using Stream API

Java program to iterate through an ArrayList of objects with Java 8 stream API.

Create a stream of elements from the list with the method stream.foreach() and get elements one by one.

ArrayList<String> namesList 
	= new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );

namesList.forEach(name -> System.out.println(name));

Let me know your thoughts on this article on how to read from ArrayList.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.