Iterate Over ArrayList Elements
In the previous post, we have seen how to find the size of ArrayList.In this post, we will see how to iterate over ArrayList elements.
There are 4 ways to iterate over the ArrayList.
- For Loop
- For each loop
- While loop
- Itearator
Let’s understand them one by one. We use get method to fetch the value.
For Loop:
import java.util.ArrayList; public class ArrayListEx { public static void main(String[] args) { ArrayList<String> cityList = new ArrayList<String>(); cityList.add("Bangalore"); cityList.add("Delhi"); cityList.add("Pune"); cityList.add("Noida"); int totalSize = cityList.size(); for(int i=0;i<totalSize;i++){ System.out.println(cityList.get(i)); } } }
Output:
Bangalore
Delhi
Pune
Noida
Delhi
Pune
Noida
For Each Loop:
Syntax:
for(DataType variable : collections)
Example:
import java.util.ArrayList; public class ArrayListEx { public static void main(String[] args) { ArrayList<String> cityList = new ArrayList<String>(); cityList.add("Bangalore"); cityList.add("Delhi"); cityList.add("Pune"); cityList.add("Noida"); for(String city : cityList){ //For each loop System.out.println(city); } } }
Output:
Bangalore
Delhi
Pune
Noida
Delhi
Pune
Noida
While Loop:
import java.util.ArrayList; public class ArrayListEx { public static void main(String[] args) { ArrayList<String> cityList = new ArrayList<String>(); cityList.add("Bangalore"); cityList.add("Delhi"); cityList.add("Pune"); cityList.add("Noida"); int count =0; while(cityList.size() > count){ System.out.println(cityList.get(count)); count++; } } }
Output:
Bangalore
Delhi
Pune
Noida
Delhi
Pune
Noida
Iterator:
It uses method ‘hasnext()‘ to check the element existence and ‘next()‘ to display the element.
import java.util.ArrayList; import java.util.Iterator; public class ArrayListEx { public static void main(String[] args) { ArrayList<String> cityList = new ArrayList<String>(); cityList.add("Bangalore"); cityList.add("Delhi"); cityList.add("Pune"); cityList.add("Noida"); Iterator iter = cityList.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } } }
Output:
Bangalore
Delhi
Pune
Noida
Delhi
Pune
Noida
Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum