- Tech Tutorials
- Monday, August 30, 2021
- How to Loop or Iterate an Arraylist in Java
- Java Example code to traverse an ArrayList
- How to loop ArrayList in Java
- How to iterate arraylist elements using Enumeration interface
- Top Related Articles:
- About the Author
- Comments
- Different Ways to Iterate an ArrayList
- How to traverse iterate or loop ArrayList in Java
Tech Tutorials
Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.
Monday, August 30, 2021
How to Loop or Iterate an Arraylist in Java
There are many ways to loop or iterate an ArrayList in Java. We can use the simple for loop, for-each loop (advanced for loop) available from Java 5 onwards, iterator or ListIterator (though not a preferred way if we are just sequentially looping through the elements of a list) and from Java 8 using Java 8 forEach statement that works with stream.
- for loop
- for-each loop
- iterator
- ListIterator
- Java 8 forEach loop
Java Example code to traverse an ArrayList
Let’s see a program that will use all these ways to iterate an ArrayList in Java.
public class LoopListDemo < public static void main(String[] args) < ListcityList = new ArrayList<>(); cityList.add("Delhi"); cityList.add("Mumbai"); cityList.add("Bangalore"); cityList.add("Chennai"); cityList.add("Kolkata"); // Using for loop with size to iterate ArrayList System.out.println("With simple for loop"); for(int i = 0; i < cityList.size(); i++)< System.out.println("City Name - " + cityList.get(i)); >// Using for-each loop to iterate ArrayList System.out.println("With for-each loop - Java 5"); for(String name : cityList) < System.out.println("City Name - " + name); >// Using Iterator to iterate ArrayList System.out.println("With iterator - Java 5"); Iterator itr = cityList.iterator(); while(itr.hasNext()) < System.out.println("City Name - " + itr.next()); >// Using List Iterator - though not needed if doing sequential looping System.out.println("With List iterator - Java 5"); ListIterator ltr = cityList.listIterator(); while(ltr.hasNext()) < System.out.println("City Name - " + ltr.next()); >//Using Java 8 iterable.forEach to iterate ArrayList System.out.println("With for-each loop - Java 8"); cityList.forEach((a)->System.out.println("City Name - " + a)); //Using Java 8 iterable.forEach loop with method reference cityList.forEach(System.out::println); > >
With simple for loop City Name - Delhi City Name - Mumbai City Name - Bangalore City Name - Chennai City Name - Kolkata With for-each loop - Java 5 City Name - Delhi City Name - Mumbai City Name - Bangalore City Name - Chennai City Name - Kolkata With iterator - Java 5 City Name - Delhi City Name - Mumbai City Name - Bangalore City Name - Chennai City Name - Kolkata
In my opinion for-each loop is best way to iterate a list if you just need to traverse sequentially through a list.
With Java 8 and multi-core environment you can also use Java 8 forEach statement to take advantage of parallel computing using parallel stream. In that case you need to write it like-
cityList.parallelStream().forEach((a)->System.out.println("City Name - " + a));
That’s all for this topic How to Loop or Iterate an Arraylist in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
How to loop ArrayList in Java
Earlier we shared ArrayList example and how to initialize ArrayList in Java. In this post we are sharing how to iterate (loop) ArrayList in Java.
There are four ways to loop ArrayList:
Lets have a look at the below example – I have used all of the mentioned methods for iterating list.
import java.util.*; public class LoopExample < public static void main(String[] args) < ArrayListarrlist = new ArrayList(); arrlist.add(14); arrlist.add(7); arrlist.add(39); arrlist.add(40); /* For Loop for iterating ArrayList */ System.out.println("For Loop"); for (int counter = 0; counter < arrlist.size(); counter++) < System.out.println(arrlist.get(counter)); >/* Advanced For Loop*/ System.out.println("Advanced For Loop"); for (Integer num : arrlist) < System.out.println(num); >/* While Loop for iterating ArrayList*/ System.out.println("While Loop"); int count = 0; while (arrlist.size() > count) < System.out.println(arrlist.get(count)); count++; >/*Looping Array List using Iterator*/ System.out.println("Iterator"); Iterator iter = arrlist.iterator(); while (iter.hasNext()) < System.out.println(iter.next()); >> >
For Loop 14 7 39 40 Advanced For Loop 14 7 39 40 While Loop 14 7 39 40 Iterator 14 7 39 40
In the comment section below, Govardhan asked a question: He asked, how to iterate an ArrayList using Enumeration. Govardhan here is the code:
How to iterate arraylist elements using Enumeration interface
import java.util.Enumeration; import java.util.ArrayList; import java.util.Collections; public class EnumExample < public static void main(String[] args) < //create an ArrayList object ArrayListarrayList = new ArrayList(); //Add elements to ArrayList arrayList.add("C"); arrayList.add("C++"); arrayList.add("Java"); arrayList.add("DotNet"); arrayList.add("Perl"); // Get the Enumeration object Enumeration e = Collections.enumeration(arrayList); // Enumerate through the ArrayList elements System.out.println("ArrayList elements: "); while(e.hasMoreElements()) System.out.println(e.nextElement()); > >
ArrayList elements: C C++ Java DotNet Perl
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
Hi Govardhan, I have updated the post and added the code. You can find your answer above in the post. Let me know if you have any further question.
Use two variable, lets call them fastVariable and slowVariable. Move the fastVariable twice the speed of slowVariable. By the time fastVariable reach end of the list slowVariable will be at middle of the list. Thanks.
Hello! So I have two seperate arraylists. I am trying to display both of them on a form, but only one of them is showing up. Is it possible to loop to arrayLists and display them at the same time?
Melly, You can join both the arraylists and then loop the combined arraylist to display all the elements. Refer this: How to join ArrayList?
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 namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles") ); for(int i = 0; i
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)
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())
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)
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.
How to traverse iterate or loop ArrayList in Java
Iterating, traversing or Looping ArrayList in Java means accessing every object stored in ArrayList and performing some operations like printing them. There are many ways to iterate, traverse or Loop ArrayList in Java e.g. advanced for loop, traditional for loop with size(), By using Iterator and ListIterator along with while loop etc. All the method of Looping List in Java also applicable to ArrayList because ArrayList is an essentially List. In next section we will see a code example of Looping ArrayList in Java.
Now we know that there are multiple ways to traverse, iterate or loop ArrayList in Java, let’s see some concrete code example to know exactly How to loop ArrayList in Java. I prefer advanced for loop added in Java 1.5 along with Autoboxing, Java Enum, Generics, Varargs and static import, also known as foreach loop if I have to just iterate over Array List in Java. If I have to remove elements while iterating than using Iterator or ListIterator is the best solution.
import java.util.ArrayList ;
import java.util.Iterator ;
/**
* Java program which shows How to loop over ArrayList in Java using advanced for loop,
* traditional for loop and How to iterate ArrayList using Iterator in Java
* advantage of using Iterator for traversing ArrayList is that you can remove
* elements from Iterator while iterating.
* @author
*/
public class ArrayListLoopExample
public static void main ( String args [])
//Creating ArrayList to demonstrate How to loop and iterate over ArrayList
ArrayList < String > games = new ArrayList < String > ( 10 ) ;
games. add ( «Cricket» ) ;
games. add ( «Soccer» ) ;
games. add ( «Hockey» ) ;
games. add ( «Chess» ) ;
System. out . println ( «original Size of ArrayList : » + games. size ()) ;
//Looping over ArrayList in Java using advanced for loop
System. out . println ( «Looping over ArrayList in Java using advanced for loop» ) ;
for ( String game: games ) <
//print each element from ArrayList
System. out . println ( game ) ;
>
//You can also Loop over ArrayList using traditional for loop
System. out . println ( «Looping ArrayList in Java using simple for loop» ) ;
for ( int i = 0 ; i < games. size () ; i++ )<
String game = games. get ( i ) ;
>
//Iterating over ArrayList in Java
Iterator < String > itr = games. iterator () ;
System. out . println ( «Iterating over ArrayList in Java using Iterator» ) ;
while ( itr. hasNext ()) <
System. out . println ( «removing » + itr. next () + » from ArrayList in Java» ) ;
itr. remove () ;
>
System. out . println ( «final Size of ArrayList : » + games. size ()) ;
Output:
original Size of ArrayList : 4
Looping over ArrayList in Java using advanced for loop
Cricket
Soccer
Hockey
Chess
Looping ArrayList in Java using simple for loop
Iterating over ArrayList in Java using Iterator
removing Cricket from ArrayList in Java
removing Soccer from ArrayList in Java
removing Hockey from ArrayList in Java
removing Chess from ArrayList in Java
final Size of ArrayList : 0
That’s all on How to iterate, traverse or loop ArrayList in Java. In summary use advance for loop to loop over ArrayList in Java, its short, clean and fast but if you need to remove elements while looping use Iterator to avoid ConcurrentModificationException .