Main Tutorials

How to loop ArrayList in Java

No nonsense, four ways to loop ArrayList in Java

  1. For loop
  2. For loop (Advance)
  3. While loop
  4. Iterator loop

package com.mkyong.core;

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

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

		List<String> list = new ArrayList<String>();
		list.add("Text 1");
		list.add("Text 2");
		list.add("Text 3");

		System.out.println("#1 normal for loop");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}

		System.out.println("#2 advance for loop");
		for (String temp : list) {
			System.out.println(temp);
		}

		System.out.println("#3 while loop");
		int j = 0;
		while (list.size() > j) {
			System.out.println(list.get(j));
			j++;
		}

		System.out.println("#4 iterator");
		Iterator<String> iterator = list.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}
}

Output


#1 normal for loop
Text 1
Text 2
Text 3
#2 advance for loop
Text 1
Text 2
Text 3
#3 while loop
Text 1
Text 2
Text 3
#4 iterator
Text 1
Text 2
Text 3

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
16 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Murugan
11 years ago

nice man….very useful

Test
2 years ago

Thanks

Marie
6 years ago

what does ‘temp’ stand for?

xuisis
4 years ago
Reply to  Marie

temporary

Luki R Daniel
8 years ago

You saved my day! Thank you 🙂

fallphenix
8 years ago

that is OK

Nav
9 years ago

Your website is a blessing! Thank you

Jhonyy
10 years ago

Thank you Kong, there was No nonsense as stated in start. Straight forward and clear cut examples,

but i have 1 question as i am a beginner . why we write List but initialize it as ArrayList,

List list = new ArrayList();

ArrayList list = new ArrayList();

mkyong
8 years ago
Reply to  Jhonyy

List is an interface, ArrayList is the implementation of List

sadasda
8 years ago
Reply to  Jhonyy

list is the name of the ArrayList

Muhammad Rabieh
10 years ago

After having advance for loop do we have any use of iterator? Please explain when and where to use iterator? Thanks.

Diva
10 years ago

you can find some more details in the below link,”http://javadomain.in/arraylist-iteration-java/”

Shoaibuddin
10 years ago

Good one, Allaah bless you.

sharathkumar
11 years ago

ur site is really helpful

Anonymous
11 years ago

Indeed very useful. By the way here are couple of more ways to loop ArrayList in Java

Student
11 years ago

Wow, your site have been REALLY helpful for my current assignment, all the examples are precise and clear, easy to understand, thanks alot