Loop ArrayList in Java

java.util.ArrayList is one of the most popular collection which we now have learnt how to use and different ways of initializing ArrayList. In this example we will learn the different ways by which we can iterate through a ArrayList.

1. For Loop
2. Enhance For Loop
3. While Loop
4. Iterator

Code Snippet

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class LoopingArrayList 
{
	public static void main(String args[])
	{
		List l1 = new ArrayList();
		l1.add("String 1");
		l1.add("String 2");
		l1.add("String 3");
		
		System.out.println("**1. Using For Loop**");
		for(int i=0;i<l1.size();i++) 		 		{ 			 			System.out.println(l1.get(i)); 		 		} 		 		 		 		System.out.println("**2. Using Enhanced For Loop**"); 		 		for(String value:l1) 		 		{ 			 			System.out.println(value); 		 		} 		 		 		 		System.out.println("**3. Using While Loop"); 		 		int flag=0; 		 		while(l1.size()>flag)
		{
			System.out.println(l1.get(flag));
			flag++;
		}
		
		System.out.println("**4. Using Iterator**");
		Iterator it = l1.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}

Output

**1. Using For Loop**
String 1
String 2
String 3
**2. Using Enhanced For Loop**
String 1
String 2
String 3
**3. Using While Loop
String 1
String 2
String 3
**4. Using Iterator**
String 1
String 2
String 3

Leave a Reply

Your email address will not be published. Required fields are marked *