Iterate a List in Java
By: Dorris
This tutorial demonstrates the use of ArrayList, Iterator and a List. There are many ways to iterate a list of objects in Java. This sample program shows you the different ways of iterating through a list in Java.
In java a list object can be iterated in following ways:
- Using Iterator class
- With the help of for loop
- With the help of while loop
- Java 5 for-each loop
Following example code shows how to iterate a list object:
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class IterateAList {
public static void main(String[] argv) {
ArrayList arrJavaTechnologies = new ArrayList();
arrJavaTechnologies.add("JSP");
arrJavaTechnologies.add("Servlets");
arrJavaTechnologies.add("EJB");
arrJavaTechnologies.add("JDBC");
arrJavaTechnologies.add("JPA");
arrJavaTechnologies.add("JSF");
//Iterate with the help of Iterator class
System.out.println("Iterating with the help of Iterator class");
Iterator iterator = arrJavaTechnologies.iterator();
while(iterator.hasNext()){
System.out.println( iterator.next() );
}
//Iterate with the help of for loop
System.out.println("Iterating with the help of for loop");
for (int i=0; i< arrJavaTechnologies.size(); i++)
{
System.out.println( arrJavaTechnologies.get(i) );
}
//Iterate with the help of while loop
System.out.println("Iterating with the help of while loop");
int j=0;
while (j< arrJavaTechnologies.size())
{
System.out.println( arrJavaTechnologies.get(j) );
j++;
}
//Iterate with the help of java 5 for-each loop
System.out.println("Iterate with the help of java 5 for-each loop");
for (String element : arrJavaTechnologies) // or sArray
{
System.out.println( element );
}
}
}
Archived Comments
1. very good dude
View Tutorial By: armend markaj at 2016-01-10 13:18:52
2. Wow NIce
View Tutorial By: Zahid ALi at 2015-01-16 22:35:45
3. thank you for this summery. can some one explain the differences.
How does an Iterator intern
View Tutorial By: magmar at 2011-01-06 17:06:39
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Java program to get location meta data from an image
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program