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.
- For loop
- Advanced for loop
- LisIterator
- While loop
- Java 8 Stream
1. Iterate ArrayList with for loop
Java program to iterate through an ArrayList of objects using the standard for loop.
2. Iterate ArrayList with for-each loop
Java program to iterate through an ArrayList of objects using for-each loop.
ArrayList namesList = new ArrayList[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 namesList = new ArrayList[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 namesList = new ArrayList[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