package example;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
*
* Java program to demonstrate different ways to loop,
* iterate or traverse List in Java.
* There are three example in this program,
* first examples shows how to loop List
* using Iterator, Second Example shows Looping over List
* using advanced Java 5 for loop
* while third and last examples demonstrate
* use of traditional for loop for traversing over
* a List in Java.
*
* @author Javin Paul
*/
public class ListLoopExample{
public static void main(String args[]){
//First example to iterate List in Java using Iterator
List<String> languages = Arrays.asList("Java",
"C++", "Scala", "Groovy");
//Getting Iterator from List in Java
Iterator<String> iterator = languages.iterator();
System.out.println("Iterating List in Java
using Iterator ");
//Iterating through all elements of List
while (iterator.hasNext()) {
System.out.printf("Current element in List
is %s %n", iterator.next());
}
//Second example of Iterating over List in Java
// using foreach loop
System.out.println("Looping List in Java using a
foreach loop");
for (String city : languages) {
System.out.println("List Element: " + city);
}
//Third example of Looping List using traditional for loop
for(int i =0; i<languages.size(); i++){
System.out.printf("programming language #%d in
List is : %s %n", i, languages.get(i) );
}
}
}