In this tutorial I will show you how you can iterate a list in your Java program. In this tutorial we are creating a list of Java technologies and then iterating the list and printing the data on console.
Ways to iterate a List in Java
In java a list object can be iterated in following ways:
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 );
}
}
}
Output of the program:
C:\techindex\techindex>java IterateAList Iterating with the help of Iterator class JSP Servlets EJB JDBC JPA JSF Iterating with the help of for loop JSP Servlets EJB JDBC JPA JSF Iterating with the help of while loop JSP Servlets EJB JDBC JPA JSF Iterate with the help of java 5 for-each loop JSP Servlets EJB JDBC JPA JSF C:\techindex\techindex> |
In this tutorial we have developed Java program to Iterate a list.
More Tutorials on roseindia.net for the topic Iterate a List in Java.If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.