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 use these five ways to loop through ArrayList.

1. Iterate ArrayList with Simple 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. Using 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

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode