How to Loop a List in Java


In this example we will show three different methods to loop a list in Java.

Source Code

1) Using for()

package com.beginner.examples;

import java.util.*;

public class LoopListExample1 {

	public static void main(String[] args) {

		List list = new ArrayList();
		list.add(1);
		list.add(2);
		list.add(3);

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

Output:

1
2
3

2) Using java.util.Iterator

package com.beginner.examples;

import java.util.*;

public class LoopListExample2 {

	public static void main(String[] args) {

		List list = new ArrayList();
		list.add(1);
		list.add(2);
		list.add(3);

		Iterator it = list.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}

    }
}

Output:

1
2
3

3) Using for()(advance)

package com.beginner.examples;

import java.util.*;

public class LoopListExample3 {

	public static void main(String[] args) {

		List list = new ArrayList();
		list.add(1);
		list.add(2);
		list.add(3);

		for (Object obj : list) 
		{
			System.out.println(obj);
		}

    }
}

Output:

1
2
3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments