In this post we’ll see different ways to iterate an ArrayList in Java. Your options to iterate an ArrayList are as follows-
- Using normal for loop
- Using For-Each loop (Advanced for loop), available from Java 5
- Using Iterator or ListIterator (Use ListIterator only if you want to iterate both forward and backward rather than looping an ArrayList sequentially).
- Using forEach statement available from Java 8
Iterate an ArrayList in Java Example
Here is a Java example code that shows all of the above mentioned ways to loop an ArrayList.
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class ArrayListIteration { public static void main(String[] args) { List<String> nameList = new ArrayList<String>(); // adding elements nameList.add("Adam"); nameList.add("Amy"); nameList.add("Jim"); nameList.add("Leo"); System.out.println("**Iterating using normal for loop**"); for(int i = 0; i < nameList.size(); i++){ System.out.println("Name-- " + nameList.get(i)); } System.out.println("**Iterating using For-Each loop**"); for(String name : nameList){ System.out.println("Name- " + name); } System.out.println("**Iterating using Iterator**"); // getting iterator Iterator itr = nameList.iterator(); while(itr.hasNext()){ System.out.println("Name- " + itr.next()); } System.out.println("**Iterating using ListIterator**"); ListIterator ltr = nameList.listIterator(); while(ltr.hasNext()){ System.out.println("Name- " + ltr.next()); } System.out.println("**Iterating using forEach statement**"); nameList.forEach((n)->System.out.println("Name - " + n)); } }
Output
**Iterating using normal for loop** Name-- Adam Name-- Amy Name-- Jim Name-- Leo **Iterating using For-Each loop** Name- Adam Name- Amy Name- Jim Name- Leo **Iterating using Iterator** Name- Adam Name- Amy Name- Jim Name- Leo **Iterating using ListIterator** Name- Adam Name- Amy Name- Jim Name- Leo **Iterating using forEach statement** Name - Adam Name - Amy Name - Jim Name - Leo
So these are the options for iterating an ArrayList in Java. If you just want to loop through the list sequentially for-each loop is the best option. If you want to modify while iterating then Iterator or ListIterator should be used otherwise any Structural modification to the list will result in ConcurrentModificationException being thrown.
Related Posts
- How to Remove Elements From Java ArrayList
- How to Remove Duplicate Elements From Java ArrayList
- How to Sort Java ArrayList
- How to Synchronize Java ArrayList
- Iterate a HashSet in Java
- Iterate a HashMap in Java
- ArrayList Vs CopyOnWriteArrayList in Java
- ConcurrentSkipListMap in Java
That’s all for the topic How to Iterate Java ArrayList. If something is missing or you have something to share about the topic please write a comment.
You may also like
That is a good tip especially to those new to the blogosphere.
Simple but very accurate info… Thank you for sharing this one.
A must read post!