java

How to iterate through an ArrayList in Java

In this tutorial, we are going to see different ways to iterate through an ArrayList in Java, using:

  • The for loop
  • The for-each loop
  • The while loop + Iterator

 

Method 1: Iterate through an ArrayList using for loop
import java.util.*;

public class Main {
	public static void main(String[] args) {

		List<String> lang = new ArrayList<String>();
		lang.add("Java");
		lang.add("PHP");
		lang.add("Python");

		for (int i = 0; i < lang.size(); i++) {
			System.out.println(lang.get(i));
		}
	}
}

Output:

Java
PHP
Python
 

Method 2: Iterate through an ArrayList using for-each loop
import java.util.*;

public class Main {
	public static void main(String[] args) {

		List<String> lang = new ArrayList<String>();
		lang.add("Java");
		lang.add("PHP");
		lang.add("Python");

		for (String s : lang) {
			System.out.println(s);
		}
	}
}

Output:

Java
PHP
Python
 

Method 3: Iterate through an ArrayList using while loop + Iterator
import java.util.*;

public class Main {
	public static void main(String[] args) {

		List<String> lang = new ArrayList<String>();
		lang.add("Java");
		lang.add("PHP");
		lang.add("Python");

		Iterator<String> it = lang.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output:

Java
PHP
Python
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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