In this post, we will see how can we iterate a list in java. There are four ways of iterating over a list.
- For loop
- For each loop(Java 5)
- While loop
- Iterator
Below example will help you to understand, how to iterate list in java. I am taking custom object list to understand better
1. Country.java
package org.arpit.java2blog;
public class Country {
String name;
long population;
public Country(String name, long population) {
super();
this.name = name;
this.population = population;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
2. IterateListMain.java
package org.arpit.java2blog;
import java.util.ArrayList;
import java.util.Iterator;
public class IterateListMain {
/**
* @author Arpit Mandliya
*/
public static void main(String[] args) {
Country india=new Country("India",1000);
Country japan=new Country("Japan",10000);
Country france=new Country("France",2000);
Country russia=new Country("Russia",20000);
// We are going to iterate on this list and will print
//name of the country
ArrayList countryLists=new ArrayList();
countryLists.add(india);
countryLists.add(japan);
countryLists.add(france);
countryLists.add(russia);
// For loop
System.out.println("Iterating using for loop : ");
for (int i = 0; i < countryLists.size(); i++) {
Country countryObj=countryLists.get(i);
System.out.println(countryObj.getName());
}
System.out.println("-----------------------------");
// For each loop
System.out.println("Iterating using for each loop : ");
for (Country countryObj:countryLists) {
System.out.println(countryObj.getName());
}
System.out.println("-----------------------------");
// While loop
System.out.println("Iterating using while loop : ");
int i=0;
while(i
Run it and you will get following output:
Iterating using for loop :
India
Japan
France
Russia
-----------------------------
Iterating using for each loop :
India
Japan
France
Russia
-----------------------------
Iterating using while loop :
India
Japan
France
Russia
-----------------------------
Iterating using iterator :
India
Japan
France
Russia