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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
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<countrylists.size country countryobj="countryLists.get(i);" system.out.println i iterator using : iteratorcountrylists="countryLists.iterator();" while> Run it and you will get following output: <pre name="code">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 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.