How to loop through a List in Java

Posted on at


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) );
}


}
}

 

Output:
Iterating List in Java using Iterator
Current element in List is London
Current element in List is Tokyo
Current element in List is NewYork
Current element in List is Mumbai
Looping List in Java using foreach loop
List Element: London
List Element: Tokyo
List Element: NewYork
List Element: Mumbai
City #0 in List is : London
City #1 in List is : Tokyo
City #2 in List is : NewYork
City #3 in List is : Mumbai

 



About the author

160